git.iko.soy/typeable/servant
on v0.14.1 help sign in
257 lines 9.3 kB history raw
1# Querying an API
3While defining handlers that [serve an API](Server.lhs) 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. That said, 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 the client-side functions.
5**servant** however has a way to inspect APIs, 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 occurrence of `Capture`, `ReqBody`, `QueryParam`
6and friends (see [the tutorial introduction](ApiType.lhs) for an overview). By *derive*, we mean that there's no code generation involved - the functions are defined just by the structure of the API type.
8The source for this tutorial section is a literate Haskell file, so first we need to have some language extensions and imports:
10``` haskell
11{-# LANGUAGE DataKinds #-}
12{-# LANGUAGE DeriveGeneric #-}
13{-# LANGUAGE TypeOperators #-}
15module Client where
17import Data.Aeson
18import Data.Proxy
19import GHC.Generics
20import Network.HTTP.Client (newManager, defaultManagerSettings)
21import Servant.API
22import Servant.Client
23```
25Also, we need examples for some domain specific data types:
27``` haskell
28data Position = Position
29 { xCoord :: Int
30 , yCoord :: Int
31 } deriving (Show, Generic)
33instance FromJSON Position
35newtype HelloMessage = HelloMessage { msg :: String }
36 deriving (Show, Generic)
38instance FromJSON HelloMessage
40data ClientInfo = ClientInfo
41 { clientName :: String
42 , clientEmail :: String
43 , clientAge :: Int
44 , clientInterestedIn :: [String]
45 } deriving Generic
47instance ToJSON ClientInfo
49data Email = Email
50 { from :: String
51 , to :: String
52 , subject :: String
53 , body :: String
54 } deriving (Show, Generic)
56instance FromJSON Email
57```
59Enough chitchat, let's see an example. Consider the following API type from the previous section:
61``` haskell
62type API = "position" :> Capture "x" Int :> Capture "y" Int :> Get '[JSON] Position
63 :<|> "hello" :> QueryParam "name" String :> Get '[JSON] HelloMessage
64 :<|> "marketing" :> ReqBody '[JSON] ClientInfo :> Post '[JSON] Email
65```
67What we are going to get with **servant-client** here is three functions, one to query each endpoint:
69``` haskell
70position :: Int -- ^ value for "x"
71 -> Int -- ^ value for "y"
72 -> ClientM Position
74hello :: Maybe String -- ^ an optional value for "name"
75 -> ClientM HelloMessage
77marketing :: ClientInfo -- ^ value for the request body
78 -> ClientM Email
79```
81Each function makes available as an argument any value that the response may
82depend on, as evidenced in the API type. How do we get these functions? By calling
83the function `client`. It takes one argument:
85- a `Proxy` to your API,
87``` haskell
88api :: Proxy API
89api = Proxy
91position :<|> hello :<|> marketing = client api
92```
94`client api` returns client functions for our _entire_ API, combined with `:<|>`, which we can pattern match on as above. You could say `client` "calculates" the correct type and number of client functions for the API type it is given (via a `Proxy`), as well as their implementations.
96If you have an `EmptyAPI` in your API, servant-client will hand you a value of
97type `EmptyClient` in the corresponding slot, where `data EmptyClient =
98EmptyClient`, as a way to indicate that you can't do anything useful with it.
100``` haskell ignore
101type API' = API :<|> EmptyAPI
103api' :: Proxy API'
104api' = Proxy
106(position' :<|> hello' :<|> marketing') :<|> EmptyClient = client api'
107```
109``` haskell ignore
110-- | URI scheme to use
111data Scheme =
112 Http -- ^ http://
113 | Https -- ^ https://
114 deriving
116-- | Simple data type to represent the target of HTTP requests
117-- for servant's automatically-generated clients.
118data BaseUrl = BaseUrl
119 { baseUrlScheme :: Scheme -- ^ URI scheme to use
120 , baseUrlHost :: String -- ^ host (eg "haskell.org")
121 , baseUrlPort :: Int -- ^ port (eg 80)
122 , baseUrlPath :: String -- ^ path (eg "/a/b/c")
123 }
124```
126That's it. Let's now write some code that uses our client functions.
128``` haskell
129queries :: ClientM (Position, HelloMessage, Email)
130queries = do
131 pos <- position 10 10
132 message <- hello (Just "servant")
133 em <- marketing (ClientInfo "Alp" "alp@foo.com" 26 ["haskell", "mathematics"])
134 return (pos, message, em)
136run :: IO ()
137run = do
138 manager' <- newManager defaultManagerSettings
139 res <- runClientM queries (mkClientEnv manager' (BaseUrl Http "localhost" 8081 ""))
140 case res of
141 Left err -> putStrLn $ "Error: " ++ show err
142 Right (pos, message, em) -> do
143 print pos
144 print message
145 print em
146```
148Here's the output of the above code running against the appropriate server:
150```
151Position {xCoord = 10, yCoord = 10}
152HelloMessage {msg = "Hello, servant"}
153Email {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!"}
154```
156The types of the arguments for the functions are the same as for (server-side) request handlers.
158## Changing the monad the client functions live in
160Just like `hoistServer` allows us to change the monad in which request handlers
161of a web application live in, we also have `hoistClient` for changing the monad
162in which _client functions_ live. Consider the following trivial API:
164``` haskell
165type HoistClientAPI = Get '[JSON] Int :<|> Capture "n" Int :> Post '[JSON] Int
167hoistClientAPI :: Proxy HoistClientAPI
168hoistClientAPI = Proxy
169```
171We already know how to derive client functions for this API, and as we have
172seen above they all return results in the `ClientM` monad when using `servant-client`.
173However, `ClientM` rarely (or never) is the actual monad we need to use the client
174functions in. Sometimes we need to run them in IO, sometimes in a custom monad
175stack. `hoistClient` is a very simple solution to the problem of "changing" the monad
176the clients run in.
178``` haskell ignore
179hoistClient
180 :: HasClient ClientM api -- we need a valid API
181 => Proxy api -- a Proxy to the API type
182 -> (forall a. m a -> n a) -- a "monad conversion function" (natural transformation)
183 -> Client m api -- clients in the source monad
184 -> Client n api -- result: clients in the target monad
185```
187The "conversion function" argument above, just like the ones given to `hoistServer`, must
188be able to turn an `m a` into an `n a` for any choice of type `a`.
190Let's see this in action on our example. We first derive our client functions as usual,
191with all of them returning a result in `ClientM`.
193``` haskell
194getIntClientM :: ClientM Int
195postIntClientM :: Int -> ClientM Int
196getIntClientM :<|> postIntClientM = client hoistClientAPI
197```
199And we finally decide that we want the handlers to run in IO instead, by
200"post-applying" `runClientM` to a fixed client environment.
202``` haskell
203-- our conversion function has type: forall a. ClientM a -> IO a
204-- the result has type:
205-- Client IO HoistClientAPI = IO Int :<|> (Int -> IO Int)
206getClients :: ClientEnv -> Client IO HoistClientAPI
207getClients clientEnv
208 = hoistClient hoistClientAPI
209 ( fmap (either (error . show) id)
210 . flip runClientM clientEnv
211 )
212 (client hoistClientAPI)
213```
215## Querying Streaming APIs.
217Consider the following streaming API type:
219``` haskell
220type StreamAPI = "positionStream" :> StreamGet NewlineFraming JSON (ResultStream Position)
221```
223Note that when we declared an API to serve, we specified a `StreamGenerator` as a producer of streams. Now we specify our result type as a `ResultStream`. With types that can be used both ways, if appropriate adaptors are written (in the form of `ToStreamGenerator` and `BuildFromStream` instances), then this asymmetry isn't necessary. Otherwise, if you want to share the same API across clients and servers, you can parameterize it like so:
225``` haskell ignore
226type StreamAPI f = "positionStream" :> StreamGet NewlineFraming JSON (f Position)
227type ServerStreamAPI = StreamAPI StreamGenerator
228type ClientStreamAPI = StreamAPI ResultStream
229```
231In any case, here's how we write a function to query our API:
233``` haskell
234streamAPI :: Proxy StreamAPI
235streamAPI = Proxy
237posStream :: ClientM (ResultStream Position)
239posStream = client streamAPI
240```
242And here's how to just print out all elements from a `ResultStream`, to give some idea of how to work with them.
244``` haskell
245printResultStream :: Show a => ResultStream a -> IO ()
246printResultStream (ResultStream k) = k $ \getResult ->
247 let loop = do
248 r <- getResult
249 case r of
250 Nothing -> return ()
251 Just x -> print x >> loop
252 in loop
253```
255The stream is parsed and provided incrementally. So the above loop prints out each result as soon as it is received on the stream, rather than waiting until they are all available to print them at once.
257You now know how to use **servant-client**!