Skip to content

Instantly share code, notes, and snippets.

@dawei-dev
Last active August 24, 2022 02:32
Show Gist options
  • Save dawei-dev/3257ee0499568198ef8cb0126b04046b to your computer and use it in GitHub Desktop.
Save dawei-dev/3257ee0499568198ef8cb0126b04046b to your computer and use it in GitHub Desktop.
servant client
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
import Data.Aeson
import Data.Proxy
import qualified Data.Text as T
import Network.HTTP.Client (newManager)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Servant.API
import Servant.Client
import System.Environment
data GuardianResponse = GuardianResponse {
total :: Int
} deriving (Eq, Show)
instance FromJSON GuardianResponse where
parseJSON = withObject "response" $ \o -> do
r <- o .: "response"
t <- r .: "total"
return $ GuardianResponse t
type SearchTerm = T.Text
type ApiKey = T.Text
type GuardianAPI = "search"
:> QueryParam "q" SearchTerm
:> QueryParam "api-key" ApiKey
:> Get '[JSON] GuardianResponse
guardianAPI :: Proxy GuardianAPI
guardianAPI = Proxy
search = client guardianAPI
queries :: SearchTerm -> ClientM GuardianResponse
queries q = do
t <- search (Just q) (Just "test")
return t
main :: IO ()
main = do
(x:xs) <- getArgs
manager' <- newManager tlsManagerSettings
res <- runClientM (queries (T.pack x)) (mkClientEnv manager' (BaseUrl Https "content.guardianapis.com" 443 ""))
print res
@kevroletin
Copy link

it's "response", not "reponse"

@dawei-dev
Copy link
Author

Thank you @kevroletin. It's corrected

@malteneuss
Copy link

Here is an example cabal file with all dependencies:
executable test
main-is: Main.hs
build-depends: base
, aeson
, text
, servant
, servant-client
, http-client
, http-client-tls
hs-source-dirs: app
default-language: Haskell2010

@ThoperSought
Copy link

thank you so much for this; it really helped me a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment