on 7af73d6 help sign in
servant/doc/tutorial/client.lhs
138 lines 5.2 kB history raw
1---
2title: Deriving Haskell functions to query an API
3toc: true
4---
6While defining handlers that serve an API has a lot to it, querying an API is simpler: we do not care about what happens inside the webserver, we just need to know how to talk to it and get a response back. Except that we usually have to write the querying functions by hand because the structure of the API isn't a first class citizen and can't be inspected to generate a bunch of client-side functions.
8*servant* however has a way to inspect API, because APIs are just Haskell types and (GHC) Haskell lets us do quite a few things with types. In the same way that we look at an API type to deduce the types the handlers should have, we can inspect the structure of the API to *derive* Haskell functions that take one argument for each occurence of `Capture`, `ReqBody`, `QueryParam`
9and friends. By *derive*, we mean that there's no code generation involved, the functions are defined just by the structure of the API type.
11The source for this tutorial section is a literate haskell file, so first we
12need to have some language extensions and imports:
14> {-# LANGUAGE DataKinds #-}
15> {-# LANGUAGE DeriveGeneric #-}
16> {-# LANGUAGE TypeOperators #-}
18> module Client where
20> import Control.Monad.Trans.Either
21> import Data.Aeson
22> import Data.Proxy
23> import GHC.Generics
24> import Servant.API
25> import Servant.Client
27Also, we need examples for some domain specific data types:
29> data Position = Position
30> { x :: Int
31> , y :: Int
32> } deriving (Show, Generic)
34> instance FromJSON Position
36> newtype HelloMessage = HelloMessage { msg :: String }
37> deriving (Show, Generic)
39> instance FromJSON HelloMessage
41> data ClientInfo = ClientInfo
42> { clientName :: String
43> , clientEmail :: String
44> , clientAge :: Int
45> , clientInterestedIn :: [String]
46> } deriving Generic
48> instance ToJSON ClientInfo
50> data Email = Email
51> { from :: String
52> , to :: String
53> , subject :: String
54> , body :: String
55> } deriving (Show, Generic)
57> instance FromJSON Email
59Enough chitchat, let's see an example. Consider the following API type from the previous section:
61> type API = "position" :> Capture "x" Int :> Capture "y" Int :> Get '[JSON] Position
62> :<|> "hello" :> QueryParam "name" String :> Get '[JSON] HelloMessage
63> :<|> "marketing" :> ReqBody '[JSON] ClientInfo :> Post '[JSON] Email
65What we are going to get with *servant-client* here is 3 functions, one to query each endpoint:
67> position :: Int -- ^ value for "x"
68> -> Int -- ^ value for "y"
69> -> EitherT ServantError IO Position
71> hello :: Maybe String -- ^ an optional value for "name"
72> -> EitherT ServantError IO HelloMessage
74> marketing :: ClientInfo -- ^ value for the request body
75> -> EitherT ServantError IO Email
77Each function makes available as an argument any value that the response may depend on, as evidenced in the API type. How do we get these functions? Just give a `Proxy` to your API and a host to make the requests to:
79> api :: Proxy API
80> api = Proxy
82> position :<|> hello :<|> marketing = client api (BaseUrl Http "localhost" 8081)
84As you can see in the code above, we just "pattern match our way" to these functions. If we try to derive less or more functions than there are endpoints in the API, we obviously get an error. The `BaseUrl` value there is just:
86``` haskell ignore
87-- | URI scheme to use
88data Scheme =
89 Http -- ^ http://
90 | Https -- ^ https://
91 deriving
93-- | Simple data type to represent the target of HTTP requests
94-- for servant's automatically-generated clients.
95data BaseUrl = BaseUrl
96 { baseUrlScheme :: Scheme -- ^ URI scheme to use
97 , baseUrlHost :: String -- ^ host (eg "haskell.org")
98 , baseUrlPort :: Int -- ^ port (eg 80)
99 }
100```
102That's it. Let's now write some code that uses our client functions.
104> queries :: EitherT ServantError IO (Position, HelloMessage, Email)
105> queries = do
106> pos <- position 10 10
107> msg <- hello (Just "servant")
108> em <- marketing (ClientInfo "Alp" "alp@foo.com" 26 ["haskell", "mathematics"])
109> return (pos, msg, em)
111> run :: IO ()
112> run = do
113> res <- runEitherT queries
114> case res of
115> Left err -> putStrLn $ "Error: " ++ show err
116> Right (pos, msg, em) -> do
117> print pos
118> print msg
119> print em
121You can now run `dist/build/tutorial/tutorial 8` (the server) and
122`dist/build/t8-main/t8-main` (the client) to see them both in action.
124``` bash
125 $ dist/build/tutorial/tutorial 8
126 # and in another terminal:
127 $ dist/build/t8-main/t8-main
128 Position {x = 10, y = 10}
129 HelloMessage {msg = "Hello, servant"}
130 Email {from = "great@company.com", to = "alp@foo.com", subject = "Hey Alp, we miss you!", body = "Hi Alp,\n\nSince you've recently turned 26, have you checked out our latest haskell, mathematics products? Give us a visit!"}
131```
133The types of the arguments for the functions are the same as for (server-side) request handlers. You now know how to use *servant-client*!
135<div style="text-align: center;">
136 <p><a href="/tutorial/server.html">Previous page: Serving an API</a></p>
137 <p><a href="/tutorial/javascript.html">Next page: Generating javascript functions to query an API</a></p>
138</div>