Last active
August 24, 2022 02:32
-
-
Save dawei-dev/3257ee0499568198ef8cb0126b04046b to your computer and use it in GitHub Desktop.
servant client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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 | |
Thank you @kevroletin. It's corrected
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
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
it's "response", not "reponse"