3The source for this tutorial section is a literate haskell file, so first we
4need to have some language extensions and imports:
7{-# LANGUAGE DataKinds #-}
8{-# LANGUAGE TypeOperators #-}
16Consider the following informal specification of an API:
18 > The endpoint at `/users` expects a GET request with query string parameter
19 > `sortby` whose value can be one of `age` or `name` and returns a
20 > list/array of JSON objects describing users, with fields `age`, `name`,
21 > `email`, `registration_date`".
23You *should* be able to formalize that. And then use the formalized version to
24get you much of the way towards writing a web app. And all the way towards
25getting some client libraries, and documentation, and more.
27How would we describe it with **servant**? An endpoint description is a good old
31type UserAPI = "users" :> QueryParam "sortby" SortBy :> Get '[JSON] [User]
33data SortBy = Age | Name
43- `"users"` says that our endpoint will be accessible under `/users`;
44- `QueryParam "sortby" SortBy`, where `SortBy` is defined by `data SortBy = Age | Name`,
45 says that the endpoint has a query string parameter named `sortby`
46 whose value will be extracted as a value of type `SortBy`.
47- `Get '[JSON] [User]` says that the endpoint will be accessible through HTTP
48 GET requests, returning a list of users encoded as JSON. You will see
49 later how you can make use of this to make your data available under different
50 formats, the choice being made depending on the [Accept
51 header](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) specified in
53- The `:>` operator that separates the various "combinators" just lets you
54 sequence static path fragments, URL captures and other combinators. The
55 ordering only matters for static path fragments and URL captures. `"users" :>
56 "list-all" :> Get '[JSON] [User]`, equivalent to `/users/list-all`, is
57 obviously not the same as `"list-all" :> "users" :> Get '[JSON] [User]`, which
58 is equivalent to `/list-all/users`. This means that sometimes `:>` is somehow
59 equivalent to `/`, but sometimes it just lets you chain another combinator.
61We can also describe APIs with multiple endpoints by using the `:<|>`
62combinators. Here's an example:
65type UserAPI2 = "users" :> "list-all" :> Get '[JSON] [User]
66 :<|> "list-all" :> "users" :> Get '[JSON] [User]
69**servant** provides a fair amount of combinators out-of-the-box, but you can
70always write your own when you need it. Here's a quick overview of the most
71often needed the combinators that **servant** comes with.
77As you've already seen, you can use type-level strings (enabled with the
78`DataKinds` language extension) for static path fragments. Chaining
79them amounts to `/`-separating them in a URL.
82type UserAPI3 = "users" :> "list-all" :> "now" :> Get '[JSON] [User]
83 -- describes an endpoint reachable at:
84 -- /users/list-all/now
87### `Delete`, `Get`, `Patch`, `Post` and `Put`
89The `Get` combinator is defined in terms of the more general `Verb`:
91data Verb method (statusCode :: Nat) (contentType :: [*]) a
92type Get = Verb 'GET 200
95There are other predefined type synonyms for other common HTTP methods,
98type Delete = Verb 'DELETE 200
99type Patch = Verb 'PATCH 200
100type Post = Verb 'POST 200
101type Put = Verb 'PUT 200
104There are also variants that do not return a 200 status code, such
107type PostCreated = Verb 'POST 201
108type PostAccepted = Verb 'POST 202
111An endpoint always ends with a variant of the `Verb` combinator
112(unless you write your own combinators). Examples:
115type UserAPI4 = "users" :> Get '[JSON] [User]
116 :<|> "admins" :> Get '[JSON] [User]
121URL captures are segments of the path of a URL that are variable and whose actual value is
122captured and passed to the request handlers. In many web frameworks, you'll see
123it written as in `/users/:userid`, with that leading `:` denoting that `userid`
124is just some kind of variable name or placeholder. For instance, if `userid` is
125supposed to range over all integers greater or equal to 1, our endpoint will
126match requests made to `/users/1`, `/users/143` and so on.
128The `Capture` combinator in **servant** takes a (type-level) string representing
129the "name of the variable" and a type, which indicates the type we want to
130decode the "captured value" to.
133data Capture (s :: Symbol) a
134-- s :: Symbol just says that 's' must be a type-level string.
137In some web frameworks, you use regexes for captures. We use a
138[`FromHttpApiData`](https://hackage.haskell.org/package/http-api-data/docs/Web-HttpApiData.html#t:FromHttpApiData)
139class, which the captured value must be an instance of.
144type UserAPI5 = "user" :> Capture "userid" Integer :> Get '[JSON] User
145 -- equivalent to 'GET /user/:userid'
146 -- except that we explicitly say that "userid"
147 -- must be an integer
149 :<|> "user" :> Capture "userid" Integer :> DeleteNoContent '[JSON] NoContent
150 -- equivalent to 'DELETE /user/:userid'
153In the second case, `DeleteNoContent` specifies a 204 response code,
154`JSON` specifies the content types on which the handler will match,
155and `NoContent` says that the response will always be empty.
157### `QueryParam`, `QueryParams`, `QueryFlag`
159`QueryParam`, `QueryParams` and `QueryFlag` are about parameters in the query string,
160i.e., those parameters that come after the question mark
161(`?`) in URLs, like `sortby` in `/users?sortby=age`, whose value is
162set to `age`. `QueryParams` lets you specify that the query parameter
163is actually a list of values, which can be specified using
164`?param=value1¶m=value2`. This represents a list of values
165composed of `value1` and `value2`. `QueryFlag` lets you specify a
166boolean-like query parameter where a client isn't forced to specify a
167value. The absence or presence of the parameter's name in the query
168string determines whether the parameter is considered to have the
169value `True` or `False`. For instance, `/users?active` would list only
170active users whereas `/users` would list them all.
172Here are the corresponding data type declarations:
175data QueryParam (sym :: Symbol) a
176data QueryParams (sym :: Symbol) a
177data QueryFlag (sym :: Symbol)
183type UserAPI6 = "users" :> QueryParam "sortby" SortBy :> Get '[JSON] [User]
184 -- equivalent to 'GET /users?sortby={age, name}'
188Again, your handlers don't have to deserialize these things (into, for example,
189a `SortBy`). **servant** takes care of it.
193Each HTTP request can carry some additional data that the server can use in its
194*body*, and this data can be encoded in any format -- as long as the server
195understands it. This can be used for example for an endpoint for creating new
196users: instead of passing each field of the user as a separate query string
197parameter or something dirty like that, we can group all the data into a JSON
198object. This has the advantage of supporting nested objects.
200**servant**'s `ReqBody` combinator takes a list of content types in which the
201data encoded in the request body can be represented and the type of that data.
202And, as you might have guessed, you don't have to check the content type
203header, and do the deserialization yourself. We do it for you. And return `Bad
204Request` or `Unsupported Content Type` as appropriate.
206Here's the data type declaration for it:
209data ReqBody (contentTypes :: [*]) a
215type UserAPI7 = "users" :> ReqBody '[JSON] User :> Post '[JSON] User
216 -- - equivalent to 'POST /users' with a JSON object
217 -- describing a User in the request body
218 -- - returns a User encoded in JSON
220 :<|> "users" :> Capture "userid" Integer
221 :> ReqBody '[JSON] User
223 -- - equivalent to 'PUT /users/:userid' with a JSON
224 -- object describing a User in the request body
225 -- - returns a User encoded in JSON
230Request headers are used for various purposes, from caching to carrying
231auth-related data. They consist of a header name and an associated value. An
232example would be `Accept: application/json`.
234The `Header` combinator in **servant** takes a type-level string for the header
235name and the type to which we want to decode the header's value (from some
236textual representation), as illustrated below:
239data Header (sym :: Symbol) a
242Here's an example where we declare that an endpoint makes use of the
243`User-Agent` header which specifies the name of the software/library used by
244the client to send the request.
247type UserAPI8 = "users" :> Header "User-Agent" Text :> Get '[JSON] [User]
252So far, whenever we have used a combinator that carries a list of content
253types, we've always specified `'[JSON]`. However, **servant** lets you use several
254content types, and also lets you define your own content types.
256Four content types are provided out-of-the-box by the core **servant** package:
257`JSON`, `PlainText`, `FormUrlEncoded` and `OctetStream`. If for some obscure
258reason you wanted one of your endpoints to make your user data available under
259those 4 formats, you would write the API type as below:
262type UserAPI9 = "users" :> Get '[JSON, PlainText, FormUrlEncoded, OctetStream] [User]
265(There are other packages that provide other content types. For example
266**servant-lucid** and **servant-blaze** allow to generate html pages (using
267**lucid** and **blaze-html**) and both come with a content type for html.)
269We will further explain how these content types and your data types can play
270together in the [section about serving an API](Server.html).
272### Response `Headers`
274Just like an HTTP request, the response generated by a webserver can carry
275headers too. **servant** provides a `Headers` combinator that carries a list of
276`Header` types and can be used by simply wrapping the "return type" of an endpoint
280data Headers (ls :: [*]) a
283If you want to describe an endpoint that returns a "User-Count" header in each
284response, you could write it as below:
287type UserAPI10 = "users" :> Get '[JSON] (Headers '[Header "User-Count" Integer] [User])
290### Basic Authentication
292Once you've established the basic routes and semantics of your API, it's time
293to consider protecting parts of it. Authentication and authorization are broad
294and nuanced topics; as servant began to explore this space we started small
295with one of HTTP's earliest authentication schemes: [Basic
296Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication).
298When protecting endpoints with basic authentication, we need to specify two items:
3001. The **realm** of authentication as per the Basic Authentictaion spec.
3012. The datatype returned by the server after authentication is verified. This
302 is usually a `User` or `Customer` type datatype.
304With those two items in mind, *servant* provides the following combinator:
307data BasicAuth (realm :: Symbol) (userData :: *)
310Which is used like so:
314 = UserAPI -- this is public
315 :<|> BasicAuth "my-real" User :> UserAPI2 -- this is protected by auth
318### Interoperability with `wai`: `Raw`
320Finally, we also include a combinator named `Raw` that provides an escape hatch
321to the underlying low-level web library `wai`. It can be used when
322you want to plug a [wai `Application`](http://hackage.haskell.org/package/wai)
326type UserAPI11 = "users" :> Get '[JSON] [User]
330 -- requests to anything else than /users
331 -- go here, where the server will try to
332 -- find a file with the right name
336One example for this is if you want to serve a directory of static files along
337with the rest of your API. But you can plug in everything that is an
338`Application`, e.g. a whole web application written in any of the web
339frameworks that support `wai`.
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list