on 2bcaccd help sign in
servant/doc/tutorial/ApiType.lhs
372 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### `Capture`
132URL captures are segments of the path of a URL that are variable and whose actual value is
133captured and passed to the request handlers. In many web frameworks, you'll see
134it written as in `/users/:userid`, with that leading `:` denoting that `userid`
135is just some kind of variable name or placeholder. For instance, if `userid` is
136supposed to range over all integers greater or equal to 1, our endpoint will
137match requests made to `/users/1`, `/users/143` and so on.
139The `Capture` combinator in **servant** takes a (type-level) string representing
140the "name of the variable" and a type, which indicates the type we want to
141decode the "captured value" to.
143``` haskell ignore
144data Capture (s :: Symbol) a
145-- s :: Symbol just says that 's' must be a type-level string.
146```
148In some web frameworks, you use regexes for captures. We use a
149[`FromHttpApiData`](https://hackage.haskell.org/package/http-api-data/docs/Web-HttpApiData.html#t:FromHttpApiData)
150class, which the captured value must be an instance of.
152Examples:
154``` haskell
155type UserAPI5 = "user" :> Capture "userid" Integer :> Get '[JSON] User
156 -- equivalent to 'GET /user/:userid'
157 -- except that we explicitly say that "userid"
158 -- must be an integer
160 :<|> "user" :> Capture "userid" Integer :> DeleteNoContent '[JSON] NoContent
161 -- equivalent to 'DELETE /user/:userid'
162```
164In the second case, `DeleteNoContent` specifies a 204 response code,
165`JSON` specifies the content types on which the handler will match,
166and `NoContent` says that the response will always be empty.
168### `QueryParam`, `QueryParams`, `QueryFlag`
170`QueryParam`, `QueryParams` and `QueryFlag` are about parameters in the query string,
171i.e., those parameters that come after the question mark
172(`?`) in URLs, like `sortby` in `/users?sortby=age`, whose value is
173set to `age`. `QueryParams` lets you specify that the query parameter
174is actually a list of values, which can be specified using
175`?param=value1&param=value2`. This represents a list of values
176composed of `value1` and `value2`. `QueryFlag` lets you specify a
177boolean-like query parameter where a client isn't forced to specify a
178value. The absence or presence of the parameter's name in the query
179string determines whether the parameter is considered to have the
180value `True` or `False`. For instance, `/users?active` would list only
181active users whereas `/users` would list them all.
183Here are the corresponding data type declarations:
185``` haskell ignore
186data QueryParam (sym :: Symbol) a
187data QueryParams (sym :: Symbol) a
188data QueryFlag (sym :: Symbol)
189```
191Examples:
193``` haskell
194type UserAPI6 = "users" :> QueryParam "sortby" SortBy :> Get '[JSON] [User]
195 -- equivalent to 'GET /users?sortby={age, name}'
197```
199Again, your handlers don't have to deserialize these things (into, for example,
200a `SortBy`). **servant** takes care of it.
202### `ReqBody`
204Each HTTP request can carry some additional data that the server can use in its
205*body*, and this data can be encoded in any format -- as long as the server
206understands it. This can be used for example for an endpoint for creating new
207users: instead of passing each field of the user as a separate query string
208parameter or something dirty like that, we can group all the data into a JSON
209object. This has the advantage of supporting nested objects.
211**servant**'s `ReqBody` combinator takes a list of content types in which the
212data encoded in the request body can be represented and the type of that data.
213And, as you might have guessed, you don't have to check the content type
214header, and do the deserialization yourself. We do it for you. And return `Bad
215Request` or `Unsupported Content Type` as appropriate.
217Here's the data type declaration for it:
219``` haskell ignore
220data ReqBody (contentTypes :: [*]) a
221```
223Examples:
225``` haskell
226type UserAPI7 = "users" :> ReqBody '[JSON] User :> Post '[JSON] User
227 -- - equivalent to 'POST /users' with a JSON object
228 -- describing a User in the request body
229 -- - returns a User encoded in JSON
231 :<|> "users" :> Capture "userid" Integer
232 :> ReqBody '[JSON] User
233 :> Put '[JSON] User
234 -- - equivalent to 'PUT /users/:userid' with a JSON
235 -- object describing a User in the request body
236 -- - returns a User encoded in JSON
237```
239### Request `Header`s
241Request headers are used for various purposes, from caching to carrying
242auth-related data. They consist of a header name and an associated value. An
243example would be `Accept: application/json`.
245The `Header` combinator in **servant** takes a type-level string for the header
246name and the type to which we want to decode the header's value (from some
247textual representation), as illustrated below:
249``` haskell ignore
250data Header (sym :: Symbol) a
251```
253Here's an example where we declare that an endpoint makes use of the
254`User-Agent` header which specifies the name of the software/library used by
255the client to send the request.
257``` haskell
258type UserAPI8 = "users" :> Header "User-Agent" Text :> Get '[JSON] [User]
259```
261### Content types
263So far, whenever we have used a combinator that carries a list of content
264types, we've always specified `'[JSON]`. However, **servant** lets you use several
265content types, and also lets you define your own content types.
267Four content types are provided out-of-the-box by the core **servant** package:
268`JSON`, `PlainText`, `FormUrlEncoded` and `OctetStream`. If for some obscure
269reason you wanted one of your endpoints to make your user data available under
270those 4 formats, you would write the API type as below:
272``` haskell
273type UserAPI9 = "users" :> Get '[JSON, PlainText, FormUrlEncoded, OctetStream] [User]
274```
276(There are other packages that provide other content types. For example
277**servant-lucid** and **servant-blaze** allow to generate html pages (using
278**lucid** and **blaze-html**) and both come with a content type for html.)
280We will further explain how these content types and your data types can play
281together in the [section about serving an API](Server.html).
283### Response `Headers`
285Just like an HTTP request, the response generated by a webserver can carry
286headers too. **servant** provides a `Headers` combinator that carries a list of
287`Header` types and can be used by simply wrapping the "return type" of an endpoint
288with it.
290``` haskell ignore
291data Headers (ls :: [*]) a
292```
294If you want to describe an endpoint that returns a "User-Count" header in each
295response, you could write it as below:
297``` haskell
298type UserAPI10 = "users" :> Get '[JSON] (Headers '[Header "User-Count" Integer] [User])
299```
301### Basic Authentication
303Once you've established the basic routes and semantics of your API, it's time
304to consider protecting parts of it. Authentication and authorization are broad
305and nuanced topics; as servant began to explore this space we started small
306with one of HTTP's earliest authentication schemes: [Basic
307Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication).
309When protecting endpoints with basic authentication, we need to specify two items:
3111. The **realm** of authentication as per the Basic Authentication spec.
3122. The datatype returned by the server after authentication is verified. This
313 is usually a `User` or `Customer` type datatype.
315With those two items in mind, *servant* provides the following combinator:
317``` haskell ignore
318data BasicAuth (realm :: Symbol) (userData :: *)
319```
321Which is used like so:
323``` haskell
324type ProtectedAPI11
325 = UserAPI -- this is public
326 :<|> BasicAuth "my-realm" User :> UserAPI2 -- this is protected by auth
327```
329### Empty APIs
331Sometimes it is useful to be able to generalise an API over the type of some
332part of it:
334``` haskell
335type UserAPI12 innerAPI
336 = UserAPI -- this is the fixed bit of the API
337 :<|> "inner" :> innerAPI -- this lets us put various other APIs under /inner
338```
340If there is a case where you do not have anything extra to serve, you can use
341the `EmptyAPI` combinator to indicate this:
343``` haskell
344type UserAPI12Alone = UserAPI12 EmptyAPI
345```
347This also works well as a placeholder for unfinished parts of an API while it
348is under development, for when you know that there should be _something_ there
349but you don't yet know what. Think of it as similar to the unit type `()`.
351### Interoperability with `wai`: `Raw`
353Finally, we also include a combinator named `Raw` that provides an escape hatch
354to the underlying low-level web library `wai`. It can be used when
355you want to plug a [wai `Application`](http://hackage.haskell.org/package/wai)
356into your webservice:
358``` haskell
359type UserAPI13 = "users" :> Get '[JSON] [User]
360 -- a /users endpoint
362 :<|> Raw
363 -- requests to anything else than /users
364 -- go here, where the server will try to
365 -- find a file with the right name
366 -- at the right path
367```
369One example for this is if you want to serve a directory of static files along
370with the rest of your API. But you can plug in everything that is an
371`Application`, e.g. a whole web application written in any of the web
372frameworks that support `wai`.