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