git.iko.soy/typeable/servant
on 56e68bc help sign in
457 lines 17 kB history raw
1{-# LANGUAGE InstanceSigs #-}
2{-# LANGUAGE TypeFamilies #-}
3{-# LANGUAGE TypeOperators #-}
4{-# LANGUAGE FlexibleInstances #-}
5{-# LANGUAGE OverloadedStrings #-}
6{-# LANGUAGE ScopedTypeVariables #-}
7-- | This module provides 'client' which can automatically generate
8-- querying functions for each endpoint just from the type representing your
9-- API.
10module Servant.Client
11 ( client
12 , HasClient(..)
13 , module Servant.Common.BaseUrl
14 ) where
16import Control.Monad
17import Control.Monad.Trans.Either
18import Data.Aeson
19import Data.ByteString.Lazy (ByteString)
20import Data.List
21import Data.Proxy
22import Data.String.Conversions
23import Data.Text (unpack)
24import GHC.TypeLits
25import qualified Network.HTTP.Types as H
26import Servant.API
27import Servant.Common.BaseUrl
28import Servant.Common.Req
29import Servant.Common.Text
31-- * Accessing APIs as a Client
33-- | 'client' allows you to produce operations to query an API from a client.
34--
35-- > type MyApi = "books" :> Get [Book] -- GET /books
36-- > :<|> "books" :> ReqBody Book :> Post Book -- POST /books
37-- >
38-- > myApi :: Proxy MyApi
39-- > myApi = Proxy
40-- >
41-- > getAllBooks :: BaseUrl -> EitherT String IO [Book]
42-- > postNewBook :: Book -> BaseUrl -> EitherT String IO Book
43-- > (getAllBooks :<|> postNewBook) = client myApi
44client :: HasClient layout => Proxy layout -> Client layout
45client p = clientWithRoute p defReq
47-- | This class lets us define how each API combinator
48-- influences the creation of an HTTP request. It's mostly
49-- an internal class, you can just use 'client'.
50class HasClient layout where
51 type Client layout :: *
52 clientWithRoute :: Proxy layout -> Req -> Client layout
54-- | A client querying function for @a ':<|>' b@ will actually hand you
55-- one function for querying @a@ and another one for querying @b@,
56-- stitching them together with ':<|>', which really is just like a pair.
57--
58-- > type MyApi = "books" :> Get [Book] -- GET /books
59-- > :<|> "books" :> ReqBody Book :> Post Book -- POST /books
60-- >
61-- > myApi :: Proxy MyApi
62-- > myApi = Proxy
63-- >
64-- > getAllBooks :: BaseUrl -> EitherT String IO [Book]
65-- > postNewBook :: Book -> BaseUrl -> EitherT String IO Book
66-- > (getAllBooks :<|> postNewBook) = client myApi
67instance (HasClient a, HasClient b) => HasClient (a :<|> b) where
68 type Client (a :<|> b) = Client a :<|> Client b
69 clientWithRoute Proxy req =
70 clientWithRoute (Proxy :: Proxy a) req :<|>
71 clientWithRoute (Proxy :: Proxy b) req
73-- | If you use a 'Capture' in one of your endpoints in your API,
74-- the corresponding querying function will automatically take
75-- an additional argument of the type specified by your 'Capture'.
76-- That function will take care of inserting a textual representation
77-- of this value at the right place in the request path.
78--
79-- You can control how values for this type are turned into
80-- text by specifying a 'ToText' instance for your type.
81--
82-- Example:
83--
84-- > type MyApi = "books" :> Capture "isbn" Text :> Get Book
85-- >
86-- > myApi :: Proxy MyApi
87-- > myApi = Proxy
88-- >
89-- > getBook :: Text -> BaseUrl -> EitherT String IO Book
90-- > getBook = client myApi
91-- > -- then you can just use "getBook" to query that endpoint
92instance (KnownSymbol capture, ToText a, HasClient sublayout)
93 => HasClient (Capture capture a :> sublayout) where
95 type Client (Capture capture a :> sublayout) =
96 a -> Client sublayout
98 clientWithRoute Proxy req val =
99 clientWithRoute (Proxy :: Proxy sublayout) $
100 appendToPath p req
102 where p = unpack (toText val)
104-- | If you have a 'Delete' endpoint in your API, the client
105-- side querying function that is created when calling 'client'
106-- will just require an argument that specifies the scheme, host
107-- and port to send the request to.
108instance HasClient Delete where
109 type Client Delete = BaseUrl -> EitherT String IO ()
111 clientWithRoute Proxy req host =
112 void $ performRequest H.methodDelete req (== 204) host
114-- | If you have a 'Get' endpoint in your API, the client
115-- side querying function that is created when calling 'client'
116-- will just require an argument that specifies the scheme, host
117-- and port to send the request to.
118instance FromJSON result => HasClient (Get result) where
119 type Client (Get result) = BaseUrl -> EitherT String IO result
120 clientWithRoute Proxy req host =
121 performRequestJSON H.methodGet req 200 host
123-- | If you use a 'Header' in one of your endpoints in your API,
124-- the corresponding querying function will automatically take
125-- an additional argument of the type specified by your 'Header',
126-- wrapped in Maybe.
127--
128-- That function will take care of encoding this argument as Text
129-- in the request headers.
130--
131-- All you need is for your type to have a 'ToText' instance.
132--
133-- Example:
134--
135-- > newtype Referer = Referer Text
136-- > deriving (Eq, Show, FromText, ToText)
137-- >
138-- > -- GET /view-my-referer
139-- > type MyApi = "view-my-referer" :> Header "Referer" Referer :> Get Referer
140-- >
141-- > myApi :: Proxy MyApi
142-- > myApi = Proxy
143-- >
144-- > viewReferer :: Maybe Referer -> BaseUrl -> EitherT String IO Book
145-- > viewReferer = client myApi
146-- > -- then you can just use "viewRefer" to query that endpoint
147-- > -- specifying Nothing or Just "http://haskell.org/" as arguments
148instance (KnownSymbol sym, ToText a, HasClient sublayout)
149 => HasClient (Header sym a :> sublayout) where
151 type Client (Header sym a :> sublayout) =
152 Maybe a -> Client sublayout
154 clientWithRoute Proxy req mval =
155 clientWithRoute (Proxy :: Proxy sublayout) $
156 maybe req (\value -> addHeader hname value req) mval
158 where hname = symbolVal (Proxy :: Proxy sym)
160-- | If you have a 'Post' endpoint in your API, the client
161-- side querying function that is created when calling 'client'
162-- will just require an argument that specifies the scheme, host
163-- and port to send the request to.
164instance FromJSON a => HasClient (Post a) where
165 type Client (Post a) = BaseUrl -> EitherT String IO a
167 clientWithRoute Proxy req uri =
168 performRequestJSON H.methodPost req 201 uri
170-- | If you have a 'Put' endpoint in your API, the client
171-- side querying function that is created when calling 'client'
172-- will just require an argument that specifies the scheme, host
173-- and port to send the request to.
174instance FromJSON a => HasClient (Put a) where
175 type Client (Put a) = BaseUrl -> EitherT String IO a
177 clientWithRoute Proxy req host =
178 performRequestJSON H.methodPut req 200 host
180-- | If you use a 'QueryParam' in one of your endpoints in your API,
181-- the corresponding querying function will automatically take
182-- an additional argument of the type specified by your 'QueryParam',
183-- enclosed in Maybe.
184--
185-- If you give Nothing, nothing will be added to the query string.
186--
187-- If you give a non-'Nothing' value, this function will take care
188-- of inserting a textual representation of this value in the query string.
189--
190-- You can control how values for your type are turned into
191-- text by specifying a 'ToText' instance for your type.
192--
193-- Example:
194--
195-- > type MyApi = "books" :> QueryParam "author" Text :> Get [Book]
196-- >
197-- > myApi :: Proxy MyApi
198-- > myApi = Proxy
199-- >
200-- > getBooksBy :: Maybe Text -> BaseUrl -> EitherT String IO [Book]
201-- > getBooksBy = client myApi
202-- > -- then you can just use "getBooksBy" to query that endpoint.
203-- > -- 'getBooksBy Nothing' for all books
204-- > -- 'getBooksBy (Just "Isaac Asimov")' to get all books by Isaac Asimov
205instance (KnownSymbol sym, ToText a, HasClient sublayout)
206 => HasClient (QueryParam sym a :> sublayout) where
208 type Client (QueryParam sym a :> sublayout) =
209 Maybe a -> Client sublayout
211 -- if mparam = Nothing, we don't add it to the query string
212 clientWithRoute Proxy req mparam =
213 clientWithRoute (Proxy :: Proxy sublayout) $
214 maybe req (flip (appendToQueryString pname) req . Just) mparamText
216 where pname = cs pname'
217 pname' = symbolVal (Proxy :: Proxy sym)
218 mparamText = fmap toText mparam
220-- | If you use a 'QueryParams' in one of your endpoints in your API,
221-- the corresponding querying function will automatically take
222-- an additional argument, a list of values of the type specified
223-- by your 'QueryParams'.
224--
225-- If you give an empty list, nothing will be added to the query string.
226--
227-- Otherwise, this function will take care
228-- of inserting a textual representation of your values in the query string,
229-- under the same query string parameter name.
230--
231-- You can control how values for your type are turned into
232-- text by specifying a 'ToText' instance for your type.
233--
234-- Example:
235--
236-- > type MyApi = "books" :> QueryParams "authors" Text :> Get [Book]
237-- >
238-- > myApi :: Proxy MyApi
239-- > myApi = Proxy
240-- >
241-- > getBooksBy :: [Text] -> BaseUrl -> EitherT String IO [Book]
242-- > getBooksBy = client myApi
243-- > -- then you can just use "getBooksBy" to query that endpoint.
244-- > -- 'getBooksBy []' for all books
245-- > -- 'getBooksBy ["Isaac Asimov", "Robert A. Heinlein"]'
246-- > -- to get all books by Asimov and Heinlein
247instance (KnownSymbol sym, ToText a, HasClient sublayout)
248 => HasClient (QueryParams sym a :> sublayout) where
250 type Client (QueryParams sym a :> sublayout) =
251 [a] -> Client sublayout
253 clientWithRoute Proxy req paramlist =
254 clientWithRoute (Proxy :: Proxy sublayout) $
255 foldl' (\ req' -> maybe req' (flip (appendToQueryString pname) req' . Just)) req paramlist'
257 where pname = cs pname'
258 pname' = symbolVal (Proxy :: Proxy sym)
259 paramlist' = map (Just . toText) paramlist
261-- | If you use a 'QueryFlag' in one of your endpoints in your API,
262-- the corresponding querying function will automatically take
263-- an additional 'Bool' argument.
264--
265-- If you give 'False', nothing will be added to the query string.
266--
267-- Otherwise, this function will insert a value-less query string
268-- parameter under the name associated to your 'QueryFlag'.
269--
270-- Example:
271--
272-- > type MyApi = "books" :> QueryFlag "published" :> Get [Book]
273-- >
274-- > myApi :: Proxy MyApi
275-- > myApi = Proxy
276-- >
277-- > getBooks :: Bool -> BaseUrl -> EitherT String IO [Book]
278-- > getBooks = client myApi
279-- > -- then you can just use "getBooks" to query that endpoint.
280-- > -- 'getBooksBy False' for all books
281-- > -- 'getBooksBy True' to only get _already published_ books
282instance (KnownSymbol sym, HasClient sublayout)
283 => HasClient (QueryFlag sym :> sublayout) where
285 type Client (QueryFlag sym :> sublayout) =
286 Bool -> Client sublayout
288 clientWithRoute Proxy req flag =
289 clientWithRoute (Proxy :: Proxy sublayout) $
290 if flag
291 then appendToQueryString paramname Nothing req
292 else req
294 where paramname = cs $ symbolVal (Proxy :: Proxy sym)
296-- | If you use a 'MatrixParam' in one of your endpoints in your API,
297-- the corresponding querying function will automatically take
298-- an additional argument of the type specified by your 'MatrixParam',
299-- enclosed in Maybe.
300--
301-- If you give Nothing, nothing will be added to the query string.
302--
303-- If you give a non-'Nothing' value, this function will take care
304-- of inserting a textual representation of this value in the query string.
305--
306-- You can control how values for your type are turned into
307-- text by specifying a 'ToText' instance for your type.
308--
309-- Example:
310--
311-- > type MyApi = "books" :> MatrixParam "author" Text :> Get [Book]
312-- >
313-- > myApi :: Proxy MyApi
314-- > myApi = Proxy
315-- >
316-- > getBooksBy :: Maybe Text -> BaseUrl -> EitherT String IO [Book]
317-- > getBooksBy = client myApi
318-- > -- then you can just use "getBooksBy" to query that endpoint.
319-- > -- 'getBooksBy Nothing' for all books
320-- > -- 'getBooksBy (Just "Isaac Asimov")' to get all books by Isaac Asimov
321instance (KnownSymbol sym, ToText a, HasClient sublayout)
322 => HasClient (MatrixParam sym a :> sublayout) where
324 type Client (MatrixParam sym a :> sublayout) =
325 Maybe a -> Client sublayout
327 -- if mparam = Nothing, we don't add it to the query string
328 clientWithRoute Proxy req mparam =
329 clientWithRoute (Proxy :: Proxy sublayout) $
330 maybe req (flip (appendToMatrixParams pname . Just) req) mparamText
332 where pname = symbolVal (Proxy :: Proxy sym)
333 mparamText = fmap (cs . toText) mparam
335-- | If you use a 'MatrixParams' in one of your endpoints in your API,
336-- the corresponding querying function will automatically take an
337-- additional argument, a list of values of the type specified by your
338-- 'MatrixParams'.
339--
340-- If you give an empty list, nothing will be added to the query string.
341--
342-- Otherwise, this function will take care of inserting a textual
343-- representation of your values in the path segment string, under the
344-- same matrix string parameter name.
345--
346-- You can control how values for your type are turned into text by
347-- specifying a 'ToText' instance for your type.
348--
349-- Example:
350--
351-- > type MyApi = "books" :> MatrixParams "authors" Text :> Get [Book]
352-- >
353-- > myApi :: Proxy MyApi
354-- > myApi = Proxy
355-- >
356-- > getBooksBy :: [Text] -> BaseUrl -> EitherT String IO [Book]
357-- > getBooksBy = client myApi
358-- > -- then you can just use "getBooksBy" to query that endpoint.
359-- > -- 'getBooksBy []' for all books
360-- > -- 'getBooksBy ["Isaac Asimov", "Robert A. Heinlein"]'
361-- > -- to get all books by Asimov and Heinlein
362instance (KnownSymbol sym, ToText a, HasClient sublayout)
363 => HasClient (MatrixParams sym a :> sublayout) where
365 type Client (MatrixParams sym a :> sublayout) =
366 [a] -> Client sublayout
368 clientWithRoute Proxy req paramlist =
369 clientWithRoute (Proxy :: Proxy sublayout) $
370 foldl' (\ req' value -> maybe req' (flip (appendToMatrixParams pname) req' . Just . cs) value) req paramlist'
372 where pname = cs pname'
373 pname' = symbolVal (Proxy :: Proxy sym)
374 paramlist' = map (Just . toText) paramlist
376-- | If you use a 'MatrixFlag' in one of your endpoints in your API,
377-- the corresponding querying function will automatically take an
378-- additional 'Bool' argument.
379--
380-- If you give 'False', nothing will be added to the path segment.
381--
382-- Otherwise, this function will insert a value-less matrix parameter
383-- under the name associated to your 'MatrixFlag'.
384--
385-- Example:
386--
387-- > type MyApi = "books" :> MatrixFlag "published" :> Get [Book]
388-- >
389-- > myApi :: Proxy MyApi
390-- > myApi = Proxy
391-- >
392-- > getBooks :: Bool -> BaseUrl -> EitherT String IO [Book]
393-- > getBooks = client myApi
394-- > -- then you can just use "getBooks" to query that endpoint.
395-- > -- 'getBooksBy False' for all books
396-- > -- 'getBooksBy True' to only get _already published_ books
397instance (KnownSymbol sym, HasClient sublayout)
398 => HasClient (MatrixFlag sym :> sublayout) where
400 type Client (MatrixFlag sym :> sublayout) =
401 Bool -> Client sublayout
403 clientWithRoute Proxy req flag =
404 clientWithRoute (Proxy :: Proxy sublayout) $
405 if flag
406 then appendToMatrixParams paramname Nothing req
407 else req
409 where paramname = cs $ symbolVal (Proxy :: Proxy sym)
411-- | Pick a 'Method' and specify where the server you want to query is. You get
412-- back the status code and the response body as a 'ByteString'.
413instance HasClient Raw where
414 type Client Raw = H.Method -> BaseUrl -> EitherT String IO (Int, ByteString)
416 clientWithRoute :: Proxy Raw -> Req -> Client Raw
417 clientWithRoute Proxy req httpMethod host =
418 performRequest httpMethod req (const True) host
420-- | If you use a 'ReqBody' in one of your endpoints in your API,
421-- the corresponding querying function will automatically take
422-- an additional argument of the type specified by your 'ReqBody'.
423-- That function will take care of encoding this argument as JSON and
424-- of using it as the request body.
425--
426-- All you need is for your type to have a 'ToJSON' instance.
427--
428-- Example:
429--
430-- > type MyApi = "books" :> ReqBody Book :> Post Book
431-- >
432-- > myApi :: Proxy MyApi
433-- > myApi = Proxy
434-- >
435-- > addBook :: Book -> BaseUrl -> EitherT String IO Book
436-- > addBook = client myApi
437-- > -- then you can just use "addBook" to query that endpoint
438instance (ToJSON a, HasClient sublayout)
439 => HasClient (ReqBody a :> sublayout) where
441 type Client (ReqBody a :> sublayout) =
442 a -> Client sublayout
444 clientWithRoute Proxy req body =
445 clientWithRoute (Proxy :: Proxy sublayout) $
446 setRQBody (encode body) req
448-- | Make the querying function append @path@ to the request path.
449instance (KnownSymbol path, HasClient sublayout) => HasClient (path :> sublayout) where
450 type Client (path :> sublayout) = Client sublayout
452 clientWithRoute Proxy req =
453 clientWithRoute (Proxy :: Proxy sublayout) $
454 appendToPath p req
456 where p = symbolVal (Proxy :: Proxy path)