on 58ccae1 help sign in
servant/doc/tutorial/ApiType.lhs
385 lines 14 kB history raw
1# A web API as a type
3The source for this tutorial section is a literate haskell file, so first we
4need to have some language extensions and imports:
6``` haskell
7{-# LANGUAGE DataKinds #-}
8{-# LANGUAGE TypeOperators #-}
10module ApiType where
12import Data.Text
13import Data.Time (UTCTime)
14import Servant.API
15```
17Consider the following informal specification of an API:
19 > The endpoint at `/users` expects a GET request with query string parameter
20 > `sortby` whose value can be one of `age` or `name` and returns a
21 > list/array of JSON objects describing users, with fields `age`, `name`,
22 > `email`, `registration_date`".
24You *should* be able to formalize that. And then use the formalized version to
25get you much of the way towards writing a web app. And all the way towards
26getting some client libraries, and documentation, and more.
28How would we describe it with **servant**? An endpoint description is a good old
29Haskell **type**:
31``` haskell
32type UserAPI = "users" :> QueryParam "sortby" SortBy :> Get '[JSON] [User]
34data SortBy = Age | Name
36data User = User {
37 name :: String,
38 age :: Int,
39 email :: String,
40 registration_date :: UTCTime
42```
44Let's break that down:
46- `"users"` says that our endpoint will be accessible under `/users`;
47- `QueryParam "sortby" SortBy`, where `SortBy` is defined by `data SortBy = Age | Name`,
48 says that the endpoint has a query string parameter named `sortby`
49 whose value will be extracted as a value of type `SortBy`.
50- `Get '[JSON] [User]` says that the endpoint will be accessible through HTTP
51 GET requests, returning a list of users encoded as JSON. You will see
52 later how you can make use of this to make your data available under different
53 formats, the choice being made depending on the [Accept
54 header](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) specified in
55 the client's request.
56- The `:>` operator that separates the various "combinators" just lets you
57 sequence static path fragments, URL captures and other combinators. The
58 ordering only matters for static path fragments and URL captures. `"users" :>
59 "list-all" :> Get '[JSON] [User]`, equivalent to `/users/list-all`, is
60 obviously not the same as `"list-all" :> "users" :> Get '[JSON] [User]`, which
61 is equivalent to `/list-all/users`. This means that sometimes `:>` is somehow
62 equivalent to `/`, but sometimes it just lets you chain another combinator.
64Tip: If your endpoint responds to `/` (the root path), just omit any combinators
65that introduce path segments. E.g. the following api has only one endpoint on `/`:
67``` haskell
68type RootEndpoint =
69 Get '[JSON] User
70```
72We can also describe APIs with multiple endpoints by using the `:<|>`
73combinators. Here's an example:
75``` haskell
76type UserAPI2 = "users" :> "list-all" :> Get '[JSON] [User]
77 :<|> "list-all" :> "users" :> Get '[JSON] [User]
78```
80**servant** provides a fair amount of combinators out-of-the-box, but you can
81always write your own when you need it. Here's a quick overview of the most
82often needed combinators that **servant** comes with.
84## Combinators
86### Static strings
88As you've already seen, you can use type-level strings (enabled with the
89`DataKinds` language extension) for static path fragments. Chaining
90them amounts to `/`-separating them in a URL.
92``` haskell
93type UserAPI3 = "users" :> "list-all" :> "now" :> Get '[JSON] [User]
94 -- describes an endpoint reachable at:
95 -- /users/list-all/now
96```
98### `Delete`, `Get`, `Patch`, `Post` and `Put`
100The `Get` combinator is defined in terms of the more general `Verb`:
101``` haskell ignore
102data Verb method (statusCode :: Nat) (contentType :: [*]) a
103type Get = Verb 'GET 200
104```
106There are other predefined type synonyms for other common HTTP methods,
107such as e.g.:
108``` haskell ignore
109type Delete = Verb 'DELETE 200
110type Patch = Verb 'PATCH 200
111type Post = Verb 'POST 200
112type Put = Verb 'PUT 200
113```
115There are also variants that do not return a 200 status code, such
116as for example:
117``` haskell ignore
118type PostCreated = Verb 'POST 201
119type PostAccepted = Verb 'POST 202
120```
122An endpoint always ends with a variant of the `Verb` combinator
123(unless you write your own combinators). Examples:
125``` haskell
126type UserAPI4 = "users" :> Get '[JSON] [User]
127 :<|> "admins" :> Get '[JSON] [User]
128```
130### `StreamGet` and `StreamPost`
132The `StreamGet` and `StreamPost` combinators are defined in terms of the more general `Stream`
134``` haskell ignore
135data Stream (method :: k1) (framing :: *) (contentType :: *) a
136type StreamGet = Stream 'GET
137type StreamPost = Stream 'POST
138```
140These describe endpoints that return a stream of values rather than just a single value. They not only take a single content type as a parameter, but also a framing strategy -- this specifies how the individual results are delineated from one another in the stream. The three standard strategies given with Servant are `NewlineFraming`, `NetstringFraming` and `NoFraming`, but others can be written to match other protocols.
143### `Capture`
145URL captures are segments of the path of a URL that are variable and whose actual value is
146captured and passed to the request handlers. In many web frameworks, you'll see
147it written as in `/users/:userid`, with that leading `:` denoting that `userid`
148is just some kind of variable name or placeholder. For instance, if `userid` is
149supposed to range over all integers greater or equal to 1, our endpoint will
150match requests made to `/users/1`, `/users/143` and so on.
152The `Capture` combinator in **servant** takes a (type-level) string representing
153the "name of the variable" and a type, which indicates the type we want to
154decode the "captured value" to.
156``` haskell ignore
157data Capture (s :: Symbol) a
158-- s :: Symbol just says that 's' must be a type-level string.
159```
161In some web frameworks, you use regexes for captures. We use a
162[`FromHttpApiData`](https://hackage.haskell.org/package/http-api-data/docs/Web-HttpApiData.html#t:FromHttpApiData)
163class, which the captured value must be an instance of.
165Examples:
167``` haskell
168type UserAPI5 = "user" :> Capture "userid" Integer :> Get '[JSON] User
169 -- equivalent to 'GET /user/:userid'
170 -- except that we explicitly say that "userid"
171 -- must be an integer
173 :<|> "user" :> Capture "userid" Integer :> DeleteNoContent '[JSON] NoContent
174 -- equivalent to 'DELETE /user/:userid'
175```
177In the second case, `DeleteNoContent` specifies a 204 response code,
178`JSON` specifies the content types on which the handler will match,
179and `NoContent` says that the response will always be empty.
181### `QueryParam`, `QueryParams`, `QueryFlag`
183`QueryParam`, `QueryParams` and `QueryFlag` are about parameters in the query string,
184i.e., those parameters that come after the question mark
185(`?`) in URLs, like `sortby` in `/users?sortby=age`, whose value is
186set to `age`. `QueryParams` lets you specify that the query parameter
187is actually a list of values, which can be specified using
188`?param=value1&param=value2`. This represents a list of values
189composed of `value1` and `value2`. `QueryFlag` lets you specify a
190boolean-like query parameter where a client isn't forced to specify a
191value. The absence or presence of the parameter's name in the query
192string determines whether the parameter is considered to have the
193value `True` or `False`. For instance, `/users?active` would list only
194active users whereas `/users` would list them all.
196Here are the corresponding data type declarations:
198``` haskell ignore
199data QueryParam (sym :: Symbol) a
200data QueryParams (sym :: Symbol) a
201data QueryFlag (sym :: Symbol)
202```
204Examples:
206``` haskell
207type UserAPI6 = "users" :> QueryParam "sortby" SortBy :> Get '[JSON] [User]
208 -- equivalent to 'GET /users?sortby={age, name}'
210```
212Again, your handlers don't have to deserialize these things (into, for example,
213a `SortBy`). **servant** takes care of it.
215### `ReqBody`
217Each HTTP request can carry some additional data that the server can use in its
218*body*, and this data can be encoded in any format -- as long as the server
219understands it. This can be used for example for an endpoint for creating new
220users: instead of passing each field of the user as a separate query string
221parameter or something dirty like that, we can group all the data into a JSON
222object. This has the advantage of supporting nested objects.
224**servant**'s `ReqBody` combinator takes a list of content types in which the
225data encoded in the request body can be represented and the type of that data.
226And, as you might have guessed, you don't have to check the content type
227header, and do the deserialization yourself. We do it for you. And return `Bad
228Request` or `Unsupported Content Type` as appropriate.
230Here's the data type declaration for it:
232``` haskell ignore
233data ReqBody (contentTypes :: [*]) a
234```
236Examples:
238``` haskell
239type UserAPI7 = "users" :> ReqBody '[JSON] User :> Post '[JSON] User
240 -- - equivalent to 'POST /users' with a JSON object
241 -- describing a User in the request body
242 -- - returns a User encoded in JSON
244 :<|> "users" :> Capture "userid" Integer
245 :> ReqBody '[JSON] User
246 :> Put '[JSON] User
247 -- - equivalent to 'PUT /users/:userid' with a JSON
248 -- object describing a User in the request body
249 -- - returns a User encoded in JSON
250```
252### Request `Header`s
254Request headers are used for various purposes, from caching to carrying
255auth-related data. They consist of a header name and an associated value. An
256example would be `Accept: application/json`.
258The `Header` combinator in **servant** takes a type-level string for the header
259name and the type to which we want to decode the header's value (from some
260textual representation), as illustrated below:
262``` haskell ignore
263data Header (sym :: Symbol) a
264```
266Here's an example where we declare that an endpoint makes use of the
267`User-Agent` header which specifies the name of the software/library used by
268the client to send the request.
270``` haskell
271type UserAPI8 = "users" :> Header "User-Agent" Text :> Get '[JSON] [User]
272```
274### Content types
276So far, whenever we have used a combinator that carries a list of content
277types, we've always specified `'[JSON]`. However, **servant** lets you use several
278content types, and also lets you define your own content types.
280Four content types are provided out-of-the-box by the core **servant** package:
281`JSON`, `PlainText`, `FormUrlEncoded` and `OctetStream`. If for some obscure
282reason you wanted one of your endpoints to make your user data available under
283those 4 formats, you would write the API type as below:
285``` haskell
286type UserAPI9 = "users" :> Get '[JSON, PlainText, FormUrlEncoded, OctetStream] [User]
287```
289(There are other packages that provide other content types. For example
290**servant-lucid** and **servant-blaze** allow to generate html pages (using
291**lucid** and **blaze-html**) and both come with a content type for html.)
293We will further explain how these content types and your data types can play
294together in the [section about serving an API](Server.html).
296### Response `Headers`
298Just like an HTTP request, the response generated by a webserver can carry
299headers too. **servant** provides a `Headers` combinator that carries a list of
300`Header` types and can be used by simply wrapping the "return type" of an endpoint
301with it.
303``` haskell ignore
304data Headers (ls :: [*]) a
305```
307If you want to describe an endpoint that returns a "User-Count" header in each
308response, you could write it as below:
310``` haskell
311type UserAPI10 = "users" :> Get '[JSON] (Headers '[Header "User-Count" Integer] [User])
312```
314### Basic Authentication
316Once you've established the basic routes and semantics of your API, it's time
317to consider protecting parts of it. Authentication and authorization are broad
318and nuanced topics; as servant began to explore this space we started small
319with one of HTTP's earliest authentication schemes: [Basic
320Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication).
322When protecting endpoints with basic authentication, we need to specify two items:
3241. The **realm** of authentication as per the Basic Authentication spec.
3252. The datatype returned by the server after authentication is verified. This
326 is usually a `User` or `Customer` type datatype.
328With those two items in mind, *servant* provides the following combinator:
330``` haskell ignore
331data BasicAuth (realm :: Symbol) (userData :: *)
332```
334Which is used like so:
336``` haskell
337type ProtectedAPI11
338 = UserAPI -- this is public
339 :<|> BasicAuth "my-realm" User :> UserAPI2 -- this is protected by auth
340```
342### Empty APIs
344Sometimes it is useful to be able to generalise an API over the type of some
345part of it:
347``` haskell
348type UserAPI12 innerAPI
349 = UserAPI -- this is the fixed bit of the API
350 :<|> "inner" :> innerAPI -- this lets us put various other APIs under /inner
351```
353If there is a case where you do not have anything extra to serve, you can use
354the `EmptyAPI` combinator to indicate this:
356``` haskell
357type UserAPI12Alone = UserAPI12 EmptyAPI
358```
360This also works well as a placeholder for unfinished parts of an API while it
361is under development, for when you know that there should be _something_ there
362but you don't yet know what. Think of it as similar to the unit type `()`.
364### Interoperability with `wai`: `Raw`
366Finally, we also include a combinator named `Raw` that provides an escape hatch
367to the underlying low-level web library `wai`. It can be used when
368you want to plug a [wai `Application`](http://hackage.haskell.org/package/wai)
369into your webservice:
371``` haskell
372type UserAPI13 = "users" :> Get '[JSON] [User]
373 -- a /users endpoint
375 :<|> Raw
376 -- requests to anything else than /users
377 -- go here, where the server will try to
378 -- find a file with the right name
379 -- at the right path
380```
382One example for this is if you want to serve a directory of static files along
383with the rest of your API. But you can plug in everything that is an
384`Application`, e.g. a whole web application written in any of the web
385frameworks that support `wai`.