@@ -5,7 +5,7 @@ type. Can we have a webservice already?
6## A first example
6## A first example
8−Equipped with some basic knowledge about the way we represent APIs, let's now
8+Equipped with some basic knowledge about the way we represent API, let's now
9write our first webservice.
9write our first webservice.
11The source for this tutorial section is a literate haskell file, so first we
11The source for this tutorial section is a literate haskell file, so first we
@@ -18,7 +18,6 @@ need to have some language extensions and imports:
18{-# LANGUAGE GeneralizedNewtypeDeriving #-}
18{-# LANGUAGE GeneralizedNewtypeDeriving #-}
19{-# LANGUAGE MultiParamTypeClasses #-}
19{-# LANGUAGE MultiParamTypeClasses #-}
20{-# LANGUAGE OverloadedStrings #-}
20{-# LANGUAGE OverloadedStrings #-}
21−{-# LANGUAGE RankNTypes #-}
22{-# LANGUAGE ScopedTypeVariables #-}
21{-# LANGUAGE ScopedTypeVariables #-}
23{-# LANGUAGE TypeOperators #-}
22{-# LANGUAGE TypeOperators #-}
@@ -27,14 +26,14 @@ module Server where
27import Prelude ()
26import Prelude ()
28import Prelude.Compat
27import Prelude.Compat
30−import Control.Monad.Except
29+import Control.Monad.IO.Class
31import Control.Monad.Reader
30import Control.Monad.Reader
31+import Control.Monad.Trans.Except
32−import Data.Aeson
32+import Data.Aeson.Compat
33import Data.Aeson.Types
33import Data.Aeson.Types
34import Data.Attoparsec.ByteString
34import Data.Attoparsec.ByteString
35import Data.ByteString (ByteString)
35import Data.ByteString (ByteString)
36import Data.List
36import Data.List
38import Data.String.Conversions
37import Data.String.Conversions
39import Data.Time.Calendar
38import Data.Time.Calendar
40import GHC.Generics
39import GHC.Generics
@@ -46,17 +45,20 @@ import Servant
46import System.Directory
45import System.Directory
47import Text.Blaze
46import Text.Blaze
48import Text.Blaze.Html.Renderer.Utf8
47import Text.Blaze.Html.Renderer.Utf8
49−import Servant.Types.SourceT (source)
50import qualified Data.Aeson.Parser
48import qualified Data.Aeson.Parser
51import qualified Text.Blaze.Html
49import qualified Text.Blaze.Html
53+{-# LANGUAGE TypeFamilies #-}
54−**Important**: the `Servant` module comes from the **servant-server** package,
56+**Important**: the `Servant` module comes from the *servant-server* package,
55the one that lets us run webservers that implement a particular API type. It
57the one that lets us run webservers that implement a particular API type. It
56−reexports all the types from the **servant** package that let you declare API
58+reexports all the types from the *servant* package that let you declare API
57types as well as everything you need to turn your request handlers into a
59types as well as everything you need to turn your request handlers into a
58fully-fledged webserver. This means that in your applications, you can just add
60fully-fledged webserver. This means that in your applications, you can just add
59−**servant-server** as a dependency, import `Servant` and not worry about anything
61+*servant-server* as a dependency, import `Servant` and not worry about anything
62We will write a server that will serve the following API.
64We will write a server that will serve the following API.
@@ -96,6 +98,12 @@ users1 =
101+Let's also write our API type.
104+type UserAPI1 = "users" :> Get '[JSON] [User]
99We can now take care of writing the actual webservice that will handle requests
107We can now take care of writing the actual webservice that will handle requests
100to such an API. This one will be very simple, being reduced to just a single
108to such an API. This one will be very simple, being reduced to just a single
101endpoint. The type of the web application is determined by the API type,
109endpoint. The type of the web application is determined by the API type,
@@ -107,11 +115,11 @@ corresponding API type.
107The first thing to know about the `Server` type family is that behind the
115The first thing to know about the `Server` type family is that behind the
108scenes it will drive the routing, letting you focus only on the business
116scenes it will drive the routing, letting you focus only on the business
109logic. The second thing to know is that for each endpoint, your handlers will
117logic. The second thing to know is that for each endpoint, your handlers will
110−by default run in the `Handler` monad. This is overridable very
118+by default run in the `ExceptT ServantErr IO` monad. This is overridable very
111easily, as explained near the end of this guide. Third thing, the type of the
119easily, as explained near the end of this guide. Third thing, the type of the
112value returned in that monad must be the same as the second argument of the
120value returned in that monad must be the same as the second argument of the
113HTTP method combinator used for the corresponding endpoint. In our case, it
121HTTP method combinator used for the corresponding endpoint. In our case, it
114−means we must provide a handler of type `Handler [User]`. Well,
122+means we must provide a handler of type `ExceptT ServantErr IO [User]`. Well,
115we have a monad, let's just `return` our list:
123we have a monad, let's just `return` our list:
117``` haskell
125``` haskell
@@ -146,8 +154,9 @@ main = run 8081 app1
147You can put this all into a file or just grab [servant's
155You can put this all into a file or just grab [servant's
148repo](http://github.com/haskell-servant/servant) and look at the
156repo](http://github.com/haskell-servant/servant) and look at the
149−*doc/tutorial* directory. This code (the source of this web page) is in
157+*servant-examples* directory. The code we have just explored is in
150−*doc/tutorial/Server.lhs*.
158+*tutorial/T1.hs*, runnable with
159+`dist/build/tutorial/tutorial 1`.
152If you run it, you can go to `http://localhost:8081/users` in your browser or
161If you run it, you can go to `http://localhost:8081/users` in your browser or
153query it with curl and you see:
162query it with curl and you see:
@@ -183,7 +192,7 @@ users2 = [isaac, albert]
184Now, just like we separate the various endpoints in `UserAPI` with `:<|>`, we
193Now, just like we separate the various endpoints in `UserAPI` with `:<|>`, we
185are going to separate the handlers with `:<|>` too! They must be provided in
194are going to separate the handlers with `:<|>` too! They must be provided in
186−the same order as in the API type.
195+the same order as the one they appear in in the API type.
188``` haskell
197``` haskell
189server2 :: Server UserAPI2
198server2 :: Server UserAPI2
@@ -192,14 +201,15 @@ server2 = return users2
192 :<|> return isaac
201 :<|> return isaac
195−And that's it! You can run this example in the same way that we showed for
204+And that's it! You can run this example with
205+`dist/build/tutorial/tutorial 2` and check out the data available
196−`server1` and check out the data available at `/users`, `/albert` and `/isaac`.
206+at `/users`, `/albert` and `/isaac`.
198## From combinators to handler arguments
208## From combinators to handler arguments
200Fine, we can write trivial webservices easily, but none of the two above use
210Fine, we can write trivial webservices easily, but none of the two above use
201any "fancy" combinator from servant. Let's address this and use `QueryParam`,
211any "fancy" combinator from servant. Let's address this and use `QueryParam`,
202−`Capture` and `ReqBody` right away. You'll see how each occurrence of these
212+`Capture` and `ReqBody` right away. You'll see how each occurence of these
203combinators in an endpoint makes the corresponding handler receive an
213combinators in an endpoint makes the corresponding handler receive an
204argument of the appropriate type automatically. You don't have to worry about
214argument of the appropriate type automatically. You don't have to worry about
205manually looking up URL captures or query string parameters, or
215manually looking up URL captures or query string parameters, or
@@ -265,15 +275,15 @@ server3 = position
265 :<|> hello
275 :<|> hello
266 :<|> marketing
276 :<|> marketing
268− where position :: Int -> Int -> Handler Position
278+ where position :: Int -> Int -> ExceptT ServantErr IO Position
269 position x y = return (Position x y)
279 position x y = return (Position x y)
271− hello :: Maybe String -> Handler HelloMessage
281+ hello :: Maybe String -> ExceptT ServantErr IO HelloMessage
272 hello mname = return . HelloMessage $ case mname of
282 hello mname = return . HelloMessage $ case mname of
273 Nothing -> "Hello, anonymous coward"
283 Nothing -> "Hello, anonymous coward"
274 Just n -> "Hello, " ++ n
284 Just n -> "Hello, " ++ n
276− marketing :: ClientInfo -> Handler Email
286+ marketing :: ClientInfo -> ExceptT ServantErr IO Email
277 marketing clientinfo = return (emailForClient clientinfo)
287 marketing clientinfo = return (emailForClient clientinfo)
@@ -288,40 +298,42 @@ parameter might not always be there);
289 - a `ReqBody contentTypeList a` becomes an argument of type `a`;
299 - a `ReqBody contentTypeList a` becomes an argument of type `a`;
291−And that's it. Here's the example in action:
301+And that's it. You can see this example in action by running
302+`dist/build/tutorial/tutorial 3`.
294$ curl http://localhost:8081/position/1/2
305$ curl http://localhost:8081/position/1/2
295−{"xCoord":1,"yCoord":2}
306+{"x":1,"y":2}
296$ curl http://localhost:8081/hello
307$ curl http://localhost:8081/hello
297{"msg":"Hello, anonymous coward"}
308{"msg":"Hello, anonymous coward"}
298$ curl http://localhost:8081/hello?name=Alp
309$ curl http://localhost:8081/hello?name=Alp
299{"msg":"Hello, Alp"}
310{"msg":"Hello, Alp"}
300−$ curl -X POST -d '{"clientName":"Alp Mestanogullari", "clientEmail" : "alp@foo.com", "clientAge": 25, "clientInterestedIn": ["haskell", "mathematics"]}' -H 'Accept: application/json' -H 'Content-type: application/json' http://localhost:8081/marketing
311+$ curl -X POST -d '{"name":"Alp Mestanogullari", "email" : "alp@foo.com", "age": 25, "interested_in": ["haskell", "mathematics"]}' -H 'Accept: application/json' -H 'Content-type: application/json' http://localhost:8081/marketing
301{"subject":"Hey Alp Mestanogullari, we miss you!","body":"Hi Alp Mestanogullari,\n\nSince you've recently turned 25, have you checked out our latest haskell, mathematics products? Give us a visit!","to":"alp@foo.com","from":"great@company.com"}
312{"subject":"Hey Alp Mestanogullari, we miss you!","body":"Hi Alp Mestanogullari,\n\nSince you've recently turned 25, have you checked out our latest haskell, mathematics products? Give us a visit!","to":"alp@foo.com","from":"great@company.com"}
304−For reference, here's a list of some combinators from **servant**:
315+For reference, here's a list of some combinators from *servant* and for those
316+that get turned into arguments to the handlers, the type of the argument.
306− > - `Delete`, `Get`, `Patch`, `Post`, `Put`: these do not become arguments. They provide the return type of handlers, which usually is `Handler <something>`.
318+ > - `Delete`, `Get`, `Patch`, `Post`, `Put`: these do not become arguments. They provide the return type of handlers, which usually is `ExceptT ServantErr IO <something>`.
307 > - `Capture "something" a` becomes an argument of type `a`.
319 > - `Capture "something" a` becomes an argument of type `a`.
308− > - `QueryParam "something" a`, `Header "something" a` all become arguments of type `Maybe a`, because there might be no value at all specified by the client for these.
320+ > - `QueryParam "something" a`, `MatrixParam "something" a`, `Header "something" a` all become arguments of type `Maybe a`, because there might be no value at all specified by the client for these.
309− > - `QueryFlag "something"` gets turned into an argument of type `Bool`.
321+ > - `QueryFlag "something"` and `MatrixFlag "something"` get turned into arguments of type `Bool`.
310− > - `QueryParams "something" a` gets turned into an argument of type `[a]`.
322+ > - `QueryParams "something" a` and `MatrixParams "something" a` get turned into arguments of type `[a]`.
311 > - `ReqBody contentTypes a` gets turned into an argument of type `a`.
323 > - `ReqBody contentTypes a` gets turned into an argument of type `a`.
313## The `FromHttpApiData`/`ToHttpApiData` classes
325## The `FromHttpApiData`/`ToHttpApiData` classes
315−Wait... How does **servant** know how to decode the `Int`s from the URL? Or how
327+Wait... How does *servant* know how to decode the `Int`s from the URL? Or how
316−to decode a `ClientInfo` value from the request body? The following three sections will
328+to decode a `ClientInfo` value from the request body? This is what this and the
317−help us answer these questions.
329+following two sections address.
319`Capture`s and `QueryParam`s are represented by some textual value in URLs.
331`Capture`s and `QueryParam`s are represented by some textual value in URLs.
320`Header`s are similarly represented by a pair of a header name and a
332`Header`s are similarly represented by a pair of a header name and a
321corresponding (textual) value in the request's "metadata". How types are
333corresponding (textual) value in the request's "metadata". How types are
322decoded from headers, captures, and query params is expressed in a class
334decoded from headers, captures, and query params is expressed in a class
323`FromHttpApiData` (from the package
335`FromHttpApiData` (from the package
324−[**http-api-data**](http://hackage.haskell.org/package/http-api-data)):
336+[*http-api-data*](http://hackage.haskell.org/package/http-api-data)):
326``` haskell ignore
338``` haskell ignore
327class FromHttpApiData a where
339class FromHttpApiData a where
@@ -343,15 +355,15 @@ As you can see, as long as you provide either `parseUrlPiece` (for `Capture`s)
343or `parseQueryParam` (for `QueryParam`s), the other methods will be defined in
355or `parseQueryParam` (for `QueryParam`s), the other methods will be defined in
344terms of this.
356terms of this.
346−**http-api-data** provides a decent number of instances, helpers for defining new
358+*http-api-data* provides a decent number of instances, helpers for defining new
347ones, and wonderful documentation.
359ones, and wonderful documentation.
349There's not much else to say about these classes. You will need instances for
361There's not much else to say about these classes. You will need instances for
350them when using `Capture`, `QueryParam`, `QueryParams`, and `Header` with your
362them when using `Capture`, `QueryParam`, `QueryParams`, and `Header` with your
351types. You will need `FromHttpApiData` instances for server-side request
363types. You will need `FromHttpApiData` instances for server-side request
352handlers and `ToHttpApiData` instances only when using
364handlers and `ToHttpApiData` instances only when using
353−**servant-client**, as described in the [section about deriving haskell
365+*servant-client*, as described in the [section about deriving haskell
354−functions to query an API](Client.html).
366+functions to query an API](/tutorial/client.html).
356## Using content-types with your data types
368## Using content-types with your data types
@@ -359,15 +371,14 @@ The same principle was operating when decoding request bodies from JSON, and
359responses *into* JSON. (JSON is just the running example - you can do this with
371responses *into* JSON. (JSON is just the running example - you can do this with
360any content-type.)
372any content-type.)
362−This section introduces a couple of typeclasses provided by **servant** that make
374+This section introduces a couple of typeclasses provided by *servant* that make
363all of this work.
375all of this work.
365### The truth behind `JSON`
377### The truth behind `JSON`
368−What exactly is `JSON` (the type as used in `Get '[JSON] User`)? Like the 3
369−other content-types provided out of the box by **servant**, it's a really dumb
380+What exactly is `JSON`? Like the 3 other content types provided out of the box
370−data type.
381+by *servant*, it's a really dumb data type.
372``` haskell ignore
383``` haskell ignore
@@ -377,15 +388,14 @@ data OctetStream
379Obviously, this is not all there is to `JSON`, otherwise it would be quite
390Obviously, this is not all there is to `JSON`, otherwise it would be quite
380−pointless. Like most of the data types in **servant**, `JSON` is mostly there as
391+pointless. Like most of the data types in *servant*, `JSON` is mostly there as
381a special *symbol* that's associated with encoding (resp. decoding) to (resp.
392a special *symbol* that's associated with encoding (resp. decoding) to (resp.
382from) the *JSON* format. The way this association is performed can be
393from) the *JSON* format. The way this association is performed can be
383decomposed into two steps.
394decomposed into two steps.
385The first step is to provide a proper
396The first step is to provide a proper
387−[**http-media**](https://hackage.haskell.org/package/http-media-0.6.2/docs/Network-HTTP-Media.html))
397+[`MediaType`](https://hackage.haskell.org/package/http-media-0.6.2/docs/Network-HTTP-Media.html)
388−representation for `JSON`, or for your own content-types. If you look at the
398+representation for `JSON`, or for your own content types. If you look at the
389haddocks from this link, you can see that we just have to specify
399haddocks from this link, you can see that we just have to specify
390`application/json` using the appropriate functions. In our case, we can just
400`application/json` using the appropriate functions. In our case, we can just
391use `(//) :: ByteString -> ByteString -> MediaType`. The precise way to specify
401use `(//) :: ByteString -> ByteString -> MediaType`. The precise way to specify
@@ -401,14 +411,14 @@ instance Accept JSON where
403The second step is centered around the `MimeRender` and `MimeUnrender` classes.
413The second step is centered around the `MimeRender` and `MimeUnrender` classes.
404−These classes just let you specify a way to encode and decode
414+These classes just let you specify a way to respectively encode and decode
405−values into or from your content-type's representation.
415+values respectively into or from your content-type's representation.
407``` haskell ignore
417``` haskell ignore
408class Accept ctype => MimeRender ctype a where
418class Accept ctype => MimeRender ctype a where
409− mimeRender :: Proxy ctype -> a -> ByteString
419+ mimeRender :: Proxy ctype -> a -> ByteString
410 -- alternatively readable as:
420 -- alternatively readable as:
411− mimeRender :: Proxy ctype -> (a -> ByteString)
421+ mimeRender :: Proxy ctype -> (a -> ByteString)
414Given a content-type and some user type, `MimeRender` provides a function that
424Given a content-type and some user type, `MimeRender` provides a function that
@@ -434,7 +444,7 @@ class Accept ctype => MimeUnrender ctype a where
434We don't have much work to do there either, `Data.Aeson.eitherDecode` is
444We don't have much work to do there either, `Data.Aeson.eitherDecode` is
435precisely what we need. However, it only allows arrays and objects as toplevel
445precisely what we need. However, it only allows arrays and objects as toplevel
436JSON values and this has proven to get in our way more than help us so we wrote
446JSON values and this has proven to get in our way more than help us so we wrote
437−our own little function around **aeson** and **attoparsec** that allows any type of
447+our own little function around *aeson* and *attoparsec* that allows any type of
438JSON value at the toplevel of a "JSON document". Here's the definition in case
448JSON value at the toplevel of a "JSON document". Here's the definition in case
439you are curious.
449you are curious.
@@ -452,20 +462,20 @@ instance FromJSON a => MimeUnrender JSON a where
452 mimeUnrender _ = eitherDecodeLenient
462 mimeUnrender _ = eitherDecodeLenient
455−And this is all the code that lets you use `JSON` with `ReqBody`, `Get`,
465+And this is all the code that lets you use `JSON` for with `ReqBody`, `Get`,
456`Post` and friends. We can check our understanding by implementing support
466`Post` and friends. We can check our understanding by implementing support
457−for an `HTML` content-type, so that users of your webservice can access an
467+for an `HTML` content type, so that users of your webservice can access an
458HTML representation of the data they want, ready to be included in any HTML
468HTML representation of the data they want, ready to be included in any HTML
459document, e.g. using [jQuery's `load` function](https://api.jquery.com/load/),
469document, e.g. using [jQuery's `load` function](https://api.jquery.com/load/),
460simply by adding `Accept: text/html` to their request headers.
470simply by adding `Accept: text/html` to their request headers.
462−### Case-studies: **servant-blaze** and **servant-lucid**
472+### Case-studies: *servant-blaze* and *servant-lucid*
464These days, most of the haskellers who write their HTML UIs directly from
474These days, most of the haskellers who write their HTML UIs directly from
465−Haskell use either [**blaze-html**](http://hackage.haskell.org/package/blaze-html)
475+Haskell use either [blaze-html](http://hackage.haskell.org/package/blaze-html)
466−or [**lucid**](http://hackage.haskell.org/package/lucid). The best option for
476+or [lucid](http://hackage.haskell.org/package/lucid). The best option for
467−**servant** is obviously to support both (and hopefully other templating
477+*servant* is obviously to support both (and hopefully other templating
468−solutions!). We're first going to look at **lucid**:
478+solutions!).
470``` haskell
480``` haskell
471data HTMLLucid
481data HTMLLucid
@@ -473,20 +483,24 @@ data HTMLLucid
474Once again, the data type is just there as a symbol for the encoding/decoding
484Once again, the data type is just there as a symbol for the encoding/decoding
475functions, except that this time we will only worry about encoding since
485functions, except that this time we will only worry about encoding since
476−**lucid** doesn't provide a way to extract data from HTML.
486+*blaze-html* and *lucid* don't provide a way to extract data from HTML.
488+Both packages also have the same `Accept` instance for their `HTMLLucid` type.
478``` haskell
490``` haskell
479instance Accept HTMLLucid where
491instance Accept HTMLLucid where
480 contentType _ = "text" // "html" /: ("charset", "utf-8")
492 contentType _ = "text" // "html" /: ("charset", "utf-8")
483−Note that this instance uses the `(/:)` operator from **http-media** which lets
495+Note that this instance uses the `(/:)` operator from *http-media* which lets
484us specify additional information about a content-type, like the charset here.
496us specify additional information about a content-type, like the charset here.
486−The rendering instances call similar functions that take
498+The rendering instances for both packages both call similar functions that take
487types with an appropriate instance to an "abstract" HTML representation and
499types with an appropriate instance to an "abstract" HTML representation and
488then write that to a `ByteString`.
500then write that to a `ByteString`.
490``` haskell
504``` haskell
491instance ToHtml a => MimeRender HTMLLucid a where
505instance ToHtml a => MimeRender HTMLLucid a where
492 mimeRender _ = renderBS . toHtml
506 mimeRender _ = renderBS . toHtml
@@ -497,7 +511,7 @@ instance MimeRender HTMLLucid (Html a) where
497 mimeRender _ = renderBS
511 mimeRender _ = renderBS
500−For **blaze-html** everything works very similarly:
514+For *blaze-html*:
502``` haskell
516``` haskell
503-- For this tutorial to compile 'HTMLLucid' and 'HTMLBlaze' have to be
517-- For this tutorial to compile 'HTMLLucid' and 'HTMLBlaze' have to be
@@ -517,13 +531,15 @@ instance MimeRender HTMLBlaze Text.Blaze.Html.Html where
517 mimeRender _ = renderHtml
531 mimeRender _ = renderHtml
520−Both [**servant-blaze**](http://hackage.haskell.org/package/servant-blaze) and
534+Both [servant-blaze](http://hackage.haskell.org/package/servant-blaze) and
521−[**servant-lucid**](http://hackage.haskell.org/package/servant-lucid) let you use
535+[servant-lucid](http://hackage.haskell.org/package/servant-lucid) let you use
522−`HTMLLucid` and `HTMLBlaze` in any content-type list as long as you provide an instance of the
536+`HTMLLucid` in any content type list as long as you provide an instance of the
523−appropriate class (`ToMarkup` for **blaze-html**, `ToHtml` for **lucid**).
537+appropriate class (`ToMarkup` for *blaze-html*, `ToHtml` for *lucid*).
539+We can now write webservice that uses *servant-lucid* to show the `HTMLLucid`
540+content type in action. First off, imports and pragmas as usual.
525−We can now write a webservice that uses **servant-lucid** to show the `HTMLLucid`
526−content-type in action. We will be serving the following API:
542+We will be serving the following API:
528``` haskell
544``` haskell
529type PersonAPI = "persons" :> Get '[JSON, HTMLLucid] [Person]
545type PersonAPI = "persons" :> Get '[JSON, HTMLLucid] [Person]
@@ -540,7 +556,7 @@ data Person = Person
540instance ToJSON Person
556instance ToJSON Person
543−Now, let's teach **lucid** how to render a `Person` as a row in a table, and then
559+Now, let's teach *lucid* how to render a `Person` as a row in a table, and then
544a list of `Person`s as a table with a row per person.
560a list of `Person`s as a table with a row per person.
546``` haskell
562``` haskell
@@ -584,45 +600,48 @@ server4 :: Server PersonAPI
584server4 = return people
600server4 = return people
586app2 :: Application
602app2 :: Application
587−app2 = serve personAPI server4
603+app2 = serve personAPI EmptyConfig server4
590−And we're good to go:
606+And we're good to go. You can run this example with `dist/build/tutorial/tutorial 4`.
593−$ curl http://localhost:8081/persons
609+ $ curl http://localhost:8081/persons
594−[{"lastName":"Newton","firstName":"Isaac"},{"lastName":"Einstein","firstName":"Albert"}]
610+ [{"lastName":"Newton","firstName":"Isaac"},{"lastName":"Einstein","firstName":"Albert"}]
595−$ curl -H 'Accept: text/html' http://localhost:8081/persons
611+ $ curl -H 'Accept: text/html' http://localhost:8081/persons
596−<table><tr><td>first name</td><td>last name</td></tr><tr><td>Isaac</td><td>Newton</td></tr><tr><td>Albert</td><td>Einstein</td></tr></table>
612+ <table><tr><td>first name</td><td>last name</td></tr><tr><td>Isaac</td><td>Newton</td></tr><tr><td>Albert</td><td>Einstein</td></tr></table>
597−# or just point your browser to http://localhost:8081/persons
613+ # or just point your browser to http://localhost:8081/persons
600−## The `Handler` monad
616+## The `ExceptT ServantErr IO` monad
602−At the heart of the handlers is the monad they run in, namely a newtype `Handler` around `ExceptT ServerError IO`
618+At the heart of the handlers is the monad they run in, namely `ExceptT
603−([haddock documentation for `ExceptT`](http://hackage.haskell.org/package/mtl-2.2.1/docs/Control-Monad-Except.html#t:ExceptT)).
604−One might wonder: why this monad? The answer is that it is the
619+ServantErr IO`. One might wonder: why this monad? The answer is that it is the
605simplest monad with the following properties:
620simplest monad with the following properties:
607−- it lets us both return a successful result (using `return`)
622+- it lets us both return a successful result (with the `Right` branch of
608−or "fail" with a descriptive error (using `throwError`);
623+`Either`) or "fail" with a descriptive error (with the `Left` branch of
609- it lets us perform IO, which is absolutely vital since most webservices exist
625- it lets us perform IO, which is absolutely vital since most webservices exist
610−as interfaces to databases that we interact with in `IO`.
626+as interfaces to databases that we interact with in `IO`;
612Let's recall some definitions.
628Let's recall some definitions.
614``` haskell ignore
630``` haskell ignore
632+data Either e a = Left e | Right a
615-- from the 'mtl' package at
634-- from the 'mtl' package at
616−newtype ExceptT e m a = ExceptT (m (Either e a))
635+newtype ExceptT e m a = ExceptT ( m (Either e a) )
619−In short, this means that a handler of type `Handler a` is simply
638+In short, this means that a handler of type `ExceptT ServantErr IO a` is simply
620−equivalent to a computation of type `IO (Either ServerError a)`, that is, an IO
639+equivalent to a computation of type `IO (Either ServantErr a)`, that is, an IO
621action that either returns an error or a result.
640action that either returns an error or a result.
623−The module [`Control.Monad.Except`](https://hackage.haskell.org/package/mtl/docs/Control-Monad-Except.html#t:ExceptT)
642+The module [`Control.Monad.Except`](https://hackage.haskell.org/package/mtl-2.2.1/docs/Control-Monad-Except.html#t:ExceptT)
624from which `ExceptT` comes is worth looking at.
643from which `ExceptT` comes is worth looking at.
625−Perhaps most importantly, `ExceptT` and `Handler` are instances of `MonadError`, so
644+Perhaps most importantly, `ExceptT` is an instance of `MonadError`, so
626`throwError` can be used to return an error from your handler (whereas `return`
645`throwError` can be used to return an error from your handler (whereas `return`
627 is enough to return a success).
646 is enough to return a success).
@@ -632,17 +651,18 @@ kind and abort early. The next two sections cover how to do just that.
633### Performing IO
652### Performing IO
635−Other important instances from the list above are `MonadIO m => MonadIO
654+Another important instance from the list above is `MonadIO m => MonadIO
636−(ExceptT e m)`, and therefore also `MonadIO Handler` as there is a `MonadIO IO` instance.
655+(ExceptT e m)`.
637−[`MonadIO`](http://hackage.haskell.org/package/base/docs/Control-Monad-IO-Class.html#t:MonadIO)
656+[`MonadIO`](http://hackage.haskell.org/package/transformers-0.4.3.0/docs/Control-Monad-IO-Class.html)
638−is a class from the **transformers** package defined as:
657+is a class from the *transformers* package defined as:
640``` haskell ignore
659``` haskell ignore
641class Monad m => MonadIO m where
660class Monad m => MonadIO m where
642 liftIO :: IO a -> m a
661 liftIO :: IO a -> m a
664+Obviously, the `IO` monad provides a `MonadIO` instance. Hence for any type
645−So if you want to run any kind of
665+`e`, `ExceptT e IO` has a `MonadIO` instance. So if you want to run any kind of
646IO computation in your handlers, just use `liftIO`:
666IO computation in your handlers, just use `liftIO`:
648``` haskell
668``` haskell
@@ -660,16 +680,16 @@ server5 = do
660 return (FileContent filecontent)
680 return (FileContent filecontent)
663−### Failing, through `ServerError`
683+### Failing, through `ServantErr`
665If you want to explicitly fail at providing the result promised by an endpoint
685If you want to explicitly fail at providing the result promised by an endpoint
666using the appropriate HTTP status code (not found, unauthorized, etc) and some
686using the appropriate HTTP status code (not found, unauthorized, etc) and some
667−error message, all you have to do is use the `throwError` function mentioned above
687+error message, all you have to do is use the `left` function mentioned above
668−and provide it with the appropriate value of type `ServerError`, which is
688+and provide it with the appropriate value of type `ServantErr`, which is
669defined as:
689defined as:
671``` haskell ignore
691``` haskell ignore
672−data ServerError = ServerError
692+data ServantErr = ServantErr
673 { errHTTPCode :: Int
693 { errHTTPCode :: Int
674 , errReasonPhrase :: String
694 , errReasonPhrase :: String
675 , errBody :: ByteString -- lazy bytestring
695 , errBody :: ByteString -- lazy bytestring
@@ -682,10 +702,10 @@ module. If you want to use these values but add a body or some headers, just
682use record update syntax:
702use record update syntax:
684``` haskell
704``` haskell
685−failingHandler :: Handler ()
705+failingHandler :: ExceptT ServantErr IO ()
686−failingHandler = throwError myerr
706+failingHandler = throwE myerr
688− where myerr :: ServerError
708+ where myerr :: ServantErr
689 myerr = err503 { errBody = "Sorry dear user." }
709 myerr = err503 { errBody = "Sorry dear user." }
@@ -698,41 +718,42 @@ server6 = do
698 exists <- liftIO (doesFileExist "myfile.txt")
718 exists <- liftIO (doesFileExist "myfile.txt")
699 if exists
719 if exists
700 then liftIO (readFile "myfile.txt") >>= return . FileContent
720 then liftIO (readFile "myfile.txt") >>= return . FileContent
701− else throwError custom404Err
721+ else throwE custom404Err
703 where custom404Err = err404 { errBody = "myfile.txt just isn't there, please leave this server alone." }
723 where custom404Err = err404 { errBody = "myfile.txt just isn't there, please leave this server alone." }
706−Here's how that server looks in action:
726+Let's run this server (`dist/build/tutorial/tutorial 5`) and
727+query it, first without the file and then with the file.
709−$ curl --verbose http://localhost:8081/myfile.txt
730+ $ curl --verbose http://localhost:8081/myfile.txt
711−* Connected to localhost (127.0.0.1) port 8081 (#0)
732+ * Connected to localhost (127.0.0.1) port 8081 (#0)
712−> GET /myfile.txt HTTP/1.1
733+ > GET /myfile.txt HTTP/1.1
713−> User-Agent: curl/7.30.0
734+ > User-Agent: curl/7.30.0
714−> Host: localhost:8081
735+ > Host: localhost:8081
715−> Accept: */*
736+ > Accept: */*
717−< HTTP/1.1 404 Not Found
738+ < HTTP/1.1 404 Not Found
719−myfile.txt just isn't there, please leave this server alone.
740+ myfile.txt just isnt there, please leave this server alone.
721−$ echo Hello > myfile.txt
742+ $ echo Hello > myfile.txt
723−$ curl --verbose http://localhost:8081/myfile.txt
744+ $ curl --verbose http://localhost:8081/myfile.txt
725−* Connected to localhost (127.0.0.1) port 8081 (#0)
746+ * Connected to localhost (127.0.0.1) port 8081 (#0)
726−> GET /myfile.txt HTTP/1.1
747+ > GET /myfile.txt HTTP/1.1
727−> User-Agent: curl/7.30.0
748+ > User-Agent: curl/7.30.0
728−> Host: localhost:8081
749+ > Host: localhost:8081
729−> Accept: */*
750+ > Accept: */*
731−< HTTP/1.1 200 OK
752+ < HTTP/1.1 200 OK
733−< Content-Type: application/json
754+ < Content-Type: application/json
735−{"content":"Hello\n"}
756+ {"content":"Hello\n"}
738## Response headers
759## Response headers
@@ -748,77 +769,151 @@ myHandler :: Server MyHandler
748myHandler = return $ addHeader 1797 albert
769myHandler = return $ addHeader 1797 albert
751−Note that the type of `addHeader header x` is different than the type of `x`!
772+Note that the type of `addHeader x` is different than the type of `x`!
752−And if you add more headers, more headers will appear in the header list:
755−type MyHeadfulHandler = Get '[JSON] (Headers '[Header "X-A-Bool" Bool, Header "X-An-Int" Int] User)
757−myHeadfulHandler :: Server MyHeadfulHandler
758−myHeadfulHandler = return $ addHeader True $ addHeader 1797 albert
761−But what if your handler only *sometimes* adds a header? If you declare that
762−your handler adds headers, and you don't add one, the return type of your
763−handler will be different than expected. To solve this, you have to explicitly
764−*not* add a header by using `noHeader`:
767−type MyMaybeHeaderHandler
768− = Capture "withHeader" Bool :> Get '[JSON] (Headers '[Header "X-An-Int" Int] User)
770−myMaybeHeaderHandler :: Server MyMaybeHeaderHandler
771−myMaybeHeaderHandler x = return $ if x then addHeader 1797 albert
772− else noHeader albert
775## Serving static files
774## Serving static files
777−**servant-server** also provides a way to just serve the content of a directory
776+*servant-server* also provides a way to just serve the content of a directory
778under some path in your web API. As mentioned earlier in this document, the
777under some path in your web API. As mentioned earlier in this document, the
779`Raw` combinator can be used in your APIs to mean "plug here any WAI
778`Raw` combinator can be used in your APIs to mean "plug here any WAI
780−application". Well, **servant-server** provides a function to get a file and
779+application". Well, servant-server provides a function to get a file and
781directory serving WAI application, namely:
780directory serving WAI application, namely:
783``` haskell ignore
782``` haskell ignore
784-- exported by Servant and Servant.Server
783-- exported by Servant and Servant.Server
785−serveDirectoryWebApp :: FilePath -> Server Raw
784+serveDirectory :: FilePath -> Server Raw
788−`serveDirectoryWebApp`'s argument must be a path to a valid directory.
787+`serveDirectory`'s argument must be a path to a valid directory. You can see an
788+example below, runnable with `dist/build/tutorial/tutorial 6`
789+(you **must** run it from within the *servant-examples/* directory!), which is
790+a webserver that serves the various bits of code covered in this
790−Here's an example API that will serve some static files:
793+The API type will be the following.
792``` haskell
795``` haskell
793−type StaticAPI = "static" :> Raw
796+type CodeAPI = "code" :> Raw
796And the server:
799And the server:
798``` haskell
801``` haskell
799−staticAPI :: Proxy StaticAPI
802+codeAPI :: Proxy CodeAPI
800−staticAPI = Proxy
803+codeAPI = Proxy
803``` haskell
806``` haskell
804−server7 :: Server StaticAPI
807+server7 :: Server CodeAPI
805−server7 = serveDirectoryWebApp "static-files"
808+server7 = serveDirectory "tutorial"
807app3 :: Application
810app3 :: Application
808−app3 = serve staticAPI server7
811+app3 = serve codeAPI EmptyConfig server7
811−This server will match any request whose path starts with `/static` and will look
814+This server will match any request whose path starts with `/code` and will look
812for a file at the path described by the rest of the request path, inside the
815for a file at the path described by the rest of the request path, inside the
813− *static-files/* directory of the path you run the program from.
816+ *tutorial/* directory of the path you run the program from.
820+- If a client requests `/code/foo.txt`, the server will look for a file at
821+ `./tutorial/foo.txt` (and fail)
822+- If a client requests `/code/T1.hs`, the server will look for a file at
823+ `./tutorial/T1.hs` (and succeed)
824+- If a client requests `/code/foo/bar/baz/movie.mp4`, the server will look for
825+ a file at `./tutorial/foo/bar/baz/movie.mp4` (and fail)
827+Here is our little server in action.
830+$ curl http://localhost:8081/code/T1.hs
831+{-# LANGUAGE DataKinds #-}
832+{-# LANGUAGE TypeFamilies #-}
833+{-# LANGUAGE DeriveGeneric #-}
834+{-# LANGUAGE TypeOperators #-}
838+import Data.Time.Calendar
847+ , registration_date :: Day
848+ } deriving (Eq, Show, Generic)
850+-- orphan ToJSON instance for Day. necessary to derive one for User
851+instance ToJSON Day where
852+ -- display a day in YYYY-mm-dd format
853+ toJSON d = toJSON (showGregorian d)
857+type UserAPI = "users" :> Get '[JSON] [User]
861+ [ User "Isaac Newton" 372 "isaac@newton.co.uk" (fromGregorian 1683 3 1)
862+ , User "Albert Einstein" 136 "ae@mc2.org" (fromGregorian 1905 12 1)
815−In other words: If a client requests `/static/foo.txt`, the server will look for a file at
865+userAPI :: Proxy UserAPI
816−`./static-files/foo.txt`. If that file exists it'll succeed and serve the file.
866+userAPI = Proxy
817−If it doesn't exist, the handler will fail with a `404` status code.
867+
868+server :: Server UserAPI
869+server = return users
872+app = serve userAPI server
873+$ curl http://localhost:8081/code/tutorial.hs
875+import Network.Wai.Handler.Warp
876+import System.Environment
888+app :: String -> (Application -> IO ()) -> IO ()
898+ "9" -> T9.writeJSFiles >> f T9.app
819−`serveDirectoryWebApp` uses some standard settings that fit the use case of
902+main :: IO ()
820−serving static files for most web apps. You can find out about the other
903+main = do
821−options in the documentation of the `Servant.Server.StaticFiles` module.
904+ args <- getArgs
906+ [n] -> app n (run 8081)
911+ putStrLn "Usage:\t tutorial N"
912+ putStrLn "\t\twhere N is the number of the example you want to run."
914+$ curl http://localhost:8081/foo
823## Nested APIs
918## Nested APIs
@@ -830,7 +925,7 @@ type UserAPI3 = -- view the user with given userid, in JSON
830 Capture "userid" Int :> Get '[JSON] User
925 Capture "userid" Int :> Get '[JSON] User
832 :<|> -- delete the user with given userid. empty response
927 :<|> -- delete the user with given userid. empty response
833− Capture "userid" Int :> DeleteNoContent
928+ Capture "userid" Int :> Delete '[] ()
836We can instead factor out the `userid`:
931We can instead factor out the `userid`:
@@ -838,7 +933,7 @@ We can instead factor out the `userid`:
838``` haskell
933``` haskell
839type UserAPI4 = Capture "userid" Int :>
934type UserAPI4 = Capture "userid" Int :>
840 ( Get '[JSON] User
935 ( Get '[JSON] User
841− :<|> DeleteNoContent
936+ :<|> Delete '[] ()
@@ -846,26 +941,26 @@ However, you have to be aware that this has an effect on the type of the
846corresponding `Server`:
941corresponding `Server`:
848``` haskell ignore
943``` haskell ignore
849−Server UserAPI3 = (Int -> Handler User)
944+Server UserAPI3 = (Int -> ExceptT ServantErr IO User)
850− :<|> (Int -> Handler NoContent)
945+ :<|> (Int -> ExceptT ServantErr IO ())
852−Server UserAPI4 = Int -> ( Handler User
947+Server UserAPI4 = Int -> ( ExceptT ServantErr IO User
853− :<|> Handler NoContent
948+ :<|> ExceptT ServantErr IO ()
857In the first case, each handler receives the *userid* argument. In the latter,
952In the first case, each handler receives the *userid* argument. In the latter,
858the whole `Server` takes the *userid* and has handlers that are just
953the whole `Server` takes the *userid* and has handlers that are just
859−computations in `Handler`, with no arguments. In other words:
954+computations in `ExceptT`, with no arguments. In other words:
861``` haskell
956``` haskell
862server8 :: Server UserAPI3
957server8 :: Server UserAPI3
863server8 = getUser :<|> deleteUser
958server8 = getUser :<|> deleteUser
865− where getUser :: Int -> Handler User
960+ where getUser :: Int -> ExceptT ServantErr IO User
866 getUser _userid = error "..."
961 getUser _userid = error "..."
868− deleteUser :: Int -> Handler NoContent
963+ deleteUser :: Int -> ExceptT ServantErr IO ()
869 deleteUser _userid = error "..."
964 deleteUser _userid = error "..."
871-- notice how getUser and deleteUser
966-- notice how getUser and deleteUser
@@ -874,10 +969,10 @@ server8 = getUser :<|> deleteUser
874server9 :: Server UserAPI4
969server9 :: Server UserAPI4
875server9 userid = getUser userid :<|> deleteUser userid
970server9 userid = getUser userid :<|> deleteUser userid
877− where getUser :: Int -> Handler User
972+ where getUser :: Int -> ExceptT ServantErr IO User
878 getUser = error "..."
973 getUser = error "..."
880− deleteUser :: Int -> Handler NoContent
975+ deleteUser :: Int -> ExceptT ServantErr IO ()
881 deleteUser = error "..."
976 deleteUser = error "..."
@@ -896,13 +991,13 @@ type API1 = "users" :>
896-- we factor out the Request Body
991-- we factor out the Request Body
897type API2 = ReqBody '[JSON] User :>
992type API2 = ReqBody '[JSON] User :>
898 ( Get '[JSON] User -- just display the same user back, don't register it
993 ( Get '[JSON] User -- just display the same user back, don't register it
899− :<|> PostNoContent -- register the user. empty response
994+ :<|> Post '[JSON] () -- register the user. empty response
902-- we factor out a Header
997-- we factor out a Header
903type API3 = Header "Authorization" Token :>
998type API3 = Header "Authorization" Token :>
904 ( Get '[JSON] SecretData -- get some secret data, if authorized
999 ( Get '[JSON] SecretData -- get some secret data, if authorized
905− :<|> ReqBody '[JSON] SecretData :> PostNoContent -- add some secret data, if authorized
1000+ :<|> ReqBody '[JSON] SecretData :> Post '[] () -- add some secret data, if authorized
908newtype Token = Token ByteString
1003newtype Token = Token ByteString
@@ -915,44 +1010,44 @@ API type only at the end.
915``` haskell
1010``` haskell
916type UsersAPI =
1011type UsersAPI =
917 Get '[JSON] [User] -- list users
1012 Get '[JSON] [User] -- list users
918− :<|> ReqBody '[JSON] User :> PostNoContent -- add a user
1013+ :<|> ReqBody '[JSON] User :> Post '[] () -- add a user
919 :<|> Capture "userid" Int :>
1014 :<|> Capture "userid" Int :>
920 ( Get '[JSON] User -- view a user
1015 ( Get '[JSON] User -- view a user
921− :<|> ReqBody '[JSON] User :> PutNoContent -- update a user
1016+ :<|> ReqBody '[JSON] User :> Put '[] () -- update a user
922− :<|> DeleteNoContent -- delete a user
1017+ :<|> Delete '[] () -- delete a user
925usersServer :: Server UsersAPI
1020usersServer :: Server UsersAPI
926usersServer = getUsers :<|> newUser :<|> userOperations
1021usersServer = getUsers :<|> newUser :<|> userOperations
928− where getUsers :: Handler [User]
1023+ where getUsers :: ExceptT ServantErr IO [User]
929 getUsers = error "..."
1024 getUsers = error "..."
931− newUser :: User -> Handler NoContent
1026+ newUser :: User -> ExceptT ServantErr IO ()
932 newUser = error "..."
1027 newUser = error "..."
934 userOperations userid =
1029 userOperations userid =
935 viewUser userid :<|> updateUser userid :<|> deleteUser userid
1030 viewUser userid :<|> updateUser userid :<|> deleteUser userid
938− viewUser :: Int -> Handler User
1033+ viewUser :: Int -> ExceptT ServantErr IO User
939 viewUser = error "..."
1034 viewUser = error "..."
941− updateUser :: Int -> User -> Handler NoContent
1036+ updateUser :: Int -> User -> ExceptT ServantErr IO ()
942 updateUser = error "..."
1037 updateUser = error "..."
944− deleteUser :: Int -> Handler NoContent
1039+ deleteUser :: Int -> ExceptT ServantErr IO ()
945 deleteUser = error "..."
1040 deleteUser = error "..."
948``` haskell
1043``` haskell
949type ProductsAPI =
1044type ProductsAPI =
950 Get '[JSON] [Product] -- list products
1045 Get '[JSON] [Product] -- list products
951− :<|> ReqBody '[JSON] Product :> PostNoContent -- add a product
1046+ :<|> ReqBody '[JSON] Product :> Post '[] () -- add a product
952 :<|> Capture "productid" Int :>
1047 :<|> Capture "productid" Int :>
953 ( Get '[JSON] Product -- view a product
1048 ( Get '[JSON] Product -- view a product
954− :<|> ReqBody '[JSON] Product :> PutNoContent -- update a product
1049+ :<|> ReqBody '[JSON] Product :> Put '[] () -- update a product
955− :<|> DeleteNoContent -- delete a product
1050+ :<|> Delete '[] () -- delete a product
958data Product = Product { productId :: Int }
1053data Product = Product { productId :: Int }
@@ -960,23 +1055,23 @@ data Product = Product { productId :: Int }
960productsServer :: Server ProductsAPI
1055productsServer :: Server ProductsAPI
961productsServer = getProducts :<|> newProduct :<|> productOperations
1056productsServer = getProducts :<|> newProduct :<|> productOperations
963− where getProducts :: Handler [Product]
1058+ where getProducts :: ExceptT ServantErr IO [Product]
964 getProducts = error "..."
1059 getProducts = error "..."
966− newProduct :: Product -> Handler NoContent
1061+ newProduct :: Product -> ExceptT ServantErr IO ()
967 newProduct = error "..."
1062 newProduct = error "..."
969 productOperations productid =
1064 productOperations productid =
970 viewProduct productid :<|> updateProduct productid :<|> deleteProduct productid
1065 viewProduct productid :<|> updateProduct productid :<|> deleteProduct productid
973− viewProduct :: Int -> Handler Product
1068+ viewProduct :: Int -> ExceptT ServantErr IO Product
974 viewProduct = error "..."
1069 viewProduct = error "..."
976− updateProduct :: Int -> Product -> Handler NoContent
1071+ updateProduct :: Int -> Product -> ExceptT ServantErr IO ()
977 updateProduct = error "..."
1072 updateProduct = error "..."
979− deleteProduct :: Int -> Handler NoContent
1074+ deleteProduct :: Int -> ExceptT ServantErr IO ()
980 deleteProduct = error "..."
1075 deleteProduct = error "..."
@@ -996,49 +1091,39 @@ abstract that away:
996-- indexed by values of type 'i'
1091-- indexed by values of type 'i'
997type APIFor a i =
1092type APIFor a i =
998 Get '[JSON] [a] -- list 'a's
1093 Get '[JSON] [a] -- list 'a's
999− :<|> ReqBody '[JSON] a :> PostNoContent -- add an 'a'
1094+ :<|> ReqBody '[JSON] a :> Post '[] () -- add an 'a'
1000 :<|> Capture "id" i :>
1095 :<|> Capture "id" i :>
1001 ( Get '[JSON] a -- view an 'a' given its "identifier" of type 'i'
1096 ( Get '[JSON] a -- view an 'a' given its "identifier" of type 'i'
1002− :<|> ReqBody '[JSON] a :> PutNoContent -- update an 'a'
1097+ :<|> ReqBody '[JSON] a :> Put '[] () -- update an 'a'
1003− :<|> DeleteNoContent -- delete an 'a'
1098+ :<|> Delete '[] () -- delete an 'a'
1006-- Build the appropriate 'Server'
1101-- Build the appropriate 'Server'
1007-- given the handlers of the right type.
1102-- given the handlers of the right type.
1008−serverFor :: Handler [a] -- handler for listing of 'a's
1103+serverFor :: ExceptT ServantErr IO [a] -- handler for listing of 'a's
1009− -> (a -> Handler NoContent) -- handler for adding an 'a'
1104+ -> (a -> ExceptT ServantErr IO ()) -- handler for adding an 'a'
1010− -> (i -> Handler a) -- handler for viewing an 'a' given its identifier of type 'i'
1105+ -> (i -> ExceptT ServantErr IO a) -- handler for viewing an 'a' given its identifier of type 'i'
1011− -> (i -> a -> Handler NoContent) -- updating an 'a' with given id
1106+ -> (i -> a -> ExceptT ServantErr IO ()) -- updating an 'a' with given id
1012− -> (i -> Handler NoContent) -- deleting an 'a' given its id
1107+ -> (i -> ExceptT ServantErr IO ()) -- deleting an 'a' given its id
1013 -> Server (APIFor a i)
1108 -> Server (APIFor a i)
1014serverFor = error "..."
1109serverFor = error "..."
1015-- implementation left as an exercise. contact us on IRC
1110-- implementation left as an exercise. contact us on IRC
1016-- or the mailing list if you get stuck!
1111-- or the mailing list if you get stuck!
1019−When your API contains the `EmptyAPI` combinator, you'll want to use
1020−`emptyServer` in the corresponding slot for your server, which will simply fail
1021−with 404 whenever a request reaches it:
1024−type CombinedAPI2 = API :<|> "empty" :> EmptyAPI
1026−server11 :: Server CombinedAPI2
1027−server11 = server3 :<|> emptyServer
1030## Using another monad for your handlers
1114## Using another monad for your handlers
1032−Remember how `Server` turns combinators for HTTP methods into `Handler`? Well, actually, there's more to that. `Server` is actually a
1116+Remember how `Server` turns combinators for HTTP methods into `ExceptT
1117+ServantErr IO`? Well, actually, there's more to that. `Server` is actually a
1033simple type synonym.
1118simple type synonym.
1035``` haskell ignore
1120``` haskell ignore
1036−type Server api = ServerT api Handler
1121+type Server api = ServerT api (ExceptT ServantErr IO)
1039`ServerT` is the actual type family that computes the required types for the
1124`ServerT` is the actual type family that computes the required types for the
1040handlers that's part of the `HasServer` class. It's like `Server` except that
1125handlers that's part of the `HasServer` class. It's like `Server` except that
1041−it takes another parameter which is the monad you want your handlers to run in,
1126+it takes a third parameter which is the monad you want your handlers to run in,
1042or more generally the return types of your handlers. This third parameter is
1127or more generally the return types of your handlers. This third parameter is
1043used for specifying the return type of the handler for an endpoint, e.g when
1128used for specifying the return type of the handler for an endpoint, e.g when
1044computing `ServerT (Get '[JSON] Person) SomeMonad`. The result would be
1129computing `ServerT (Get '[JSON] Person) SomeMonad`. The result would be
@@ -1046,155 +1131,98 @@ computing `ServerT (Get '[JSON] Person) SomeMonad`. The result would be
1047The first and main question one might have then is: how do we write handlers
1132The first and main question one might have then is: how do we write handlers
1048that run in another monad? How can we "bring back" the value from a given monad
1133that run in another monad? How can we "bring back" the value from a given monad
1049−into something **servant** can understand?
1134+into something *servant* can understand?
1051### Natural transformations
1136### Natural transformations
1053If we have a function that gets us from an `m a` to an `n a`, for any `a`, what
1138If we have a function that gets us from an `m a` to an `n a`, for any `a`, what
1054do we have?
1139do we have?
1056−``` haskell
1141+``` haskell ignore
1057−type (~>) m n = forall a. m a -> n a
1142+newtype m :~> n = Nat { unNat :: forall a. m a -> n a}
1062−``` haskell
1144+-- For example
1063−listToMaybe' :: [] ~> Maybe
1145+-- listToMaybeNat ::`[] :~> Maybe`
1064−listToMaybe' = listToMaybe -- from Data.Maybe
1146+-- listToMaybeNat = Nat listToMaybe -- from Data.Maybe
1148+(`Nat` comes from "natural transformation", in case you're wondering.)
1067−Note that `servant` doesn't declare the `~>` type-alias, as the unfolded
1068−variant isn't much longer to write, as we'll see shortly.
1070−So if you want to write handlers using another monad/type than `Handler`, say the `Reader String` monad, the first thing you have to
1150+So if you want to write handlers using another monad/type than `ExceptT
1151+ServantErr IO`, say the `Reader String` monad, the first thing you have to
1071prepare is a function:
1152prepare is a function:
1073``` haskell ignore
1154``` haskell ignore
1074−readerToHandler :: Reader String a -> Handler a
1155+readerToEither :: Reader String :~> ExceptT ServantErr IO
1158+Let's start with `readerToEither'`. We obviously have to run the `Reader`
1077−We obviously have to run the `Reader` computation by supplying it with a
1159+computation by supplying it with a `String`, like `"hi"`. We get an `a` out
1078−`String`, like `"hi"`. We get an `a` out from that and can then just `return`
1160+from that and can then just `return` it into `ExceptT`. We can then just wrap
1079−it into `Handler`.
1161+that function with the `Nat` constructor to make it have the fancier type.
1081``` haskell
1163``` haskell
1082−readerToHandler :: Reader String a -> Handler a
1164+readerToEither' :: forall a. Reader String a -> ExceptT ServantErr IO a
1083−readerToHandler r = return (runReader r "hi")
1165+readerToEither' r = return (runReader r "hi")
1167+readerToEither :: Reader String :~> ExceptT ServantErr IO
1168+readerToEither = Nat readerToEither'
1086We can write some simple webservice with the handlers running in `Reader String`.
1171We can write some simple webservice with the handlers running in `Reader String`.
1088``` haskell
1173``` haskell
1089type ReaderAPI = "a" :> Get '[JSON] Int
1174type ReaderAPI = "a" :> Get '[JSON] Int
1090− :<|> "b" :> ReqBody '[JSON] Double :> Get '[JSON] Bool
1175+ :<|> "b" :> Get '[JSON] String
1092readerAPI :: Proxy ReaderAPI
1177readerAPI :: Proxy ReaderAPI
1093readerAPI = Proxy
1178readerAPI = Proxy
1095readerServerT :: ServerT ReaderAPI (Reader String)
1180readerServerT :: ServerT ReaderAPI (Reader String)
1096−readerServerT = a :<|> b where
1181+readerServerT = a :<|> b
1097− a :: Reader String Int
1183+ where a :: Reader String Int
1098− a = return 1797
1184+ a = return 1797
1100− b :: Double -> Reader String Bool
1186+ b :: Reader String String
1101− b _ = asks (== "hi")
1187+ b = ask
1104We unfortunately can't use `readerServerT` as an argument of `serve`, because
1190We unfortunately can't use `readerServerT` as an argument of `serve`, because
1105−`serve` wants a `Server ReaderAPI`, i.e., with handlers running in `Handler`. But there's a simple solution to this.
1191+`serve` wants a `Server ReaderAPI`, i.e., with handlers running in `ExceptT
1192+ServantErr IO`. But there's a simple solution to this.
1107−### Welcome `hoistServer`
1194+### Enter `enter`
1109−That's right. We have just written `readerToHandler`, which is exactly what we
1196+That's right. We have just written `readerToEither`, which is exactly what we
1110−would need to apply to all handlers to make the handlers have the
1197+would need to apply to the results of all handlers to make the handlers have the
1111right type for `serve`. Being cumbersome to do by hand, we provide a function
1198right type for `serve`. Being cumbersome to do by hand, we provide a function
1112−`hoistServer` which takes a natural transformation between two parameterized types `m`
1199+`enter` which takes a natural transformation between two parametrized types `m`
1113and `n` and a `ServerT someapi m`, and returns a `ServerT someapi n`.
1200and `n` and a `ServerT someapi m`, and returns a `ServerT someapi n`.
1115−In our case, we can wrap up our little webservice by using
1202+In our case, we can wrap up our little webservice by using `enter
1116−`hoistServer readerAPI readerToHandler` on our handlers.
1203+readerToEither` on our handlers.
1118``` haskell
1205``` haskell
1119readerServer :: Server ReaderAPI
1206readerServer :: Server ReaderAPI
1120−readerServer = hoistServer readerAPI readerToHandler readerServerT
1207+readerServer = enter readerToEither readerServerT
1122app4 :: Application
1209app4 :: Application
1123−app4 = serve readerAPI readerServer
1210+app4 = serve readerAPI EmptyConfig readerServer
1126−This is the webservice in action:
1213+And we can indeed see this webservice in action by running
1214+`dist/build/tutorial/tutorial 7`.
1129$ curl http://localhost:8081/a
1217$ curl http://localhost:8081/a
1131−$ curl http://localhost:8081/b -X GET -d '42.0' -H 'Content-Type: application/json'
1219+$ curl http://localhost:8081/b
1135−### An arrow is a reader too.
1137−In previous versions of `servant` we had an `enter` to do what `hoistServer`
1138−does now. `enter` had an ambitious design goals, but was problematic in practice.
1140−One problematic situation was when the source monad was `(->) r`, yet it's
1141−handy in practice, because `(->) r` is isomorphic to `Reader r`.
1143−We can rewrite the previous example without `Reader`:
1146−funServerT :: ServerT ReaderAPI ((->) String)
1147−funServerT = a :<|> b where
1151− -- unfortunately, we cannot make `String` the first argument.
1152− b :: Double -> String -> Bool
1153− b _ s = s == "hi"
1220+"hi"
1155−funToHandler :: (String -> a) -> Handler a
1156−funToHandler f = return (f "hi")
1159−app5 = serve readerAPI (hoistServer readerAPI funToHandler funServerT)
1162−## Streaming endpoints
1164−We can create endpoints that don't just give back a single result, but give
1165−back a *stream* of results, served one at a time. Stream endpoints only provide
1166−a single content type, and also specify what framing strategy is used to
1167−delineate the results. To serve these results, we need to give back a stream
1168−producer. Adapters can be written to *Pipes*, *Conduit* and the like, or
1169−written directly as `SourceIO`s. SourceIO builds upon servant's own `SourceT`
1170−stream type (it's simpler than *Pipes* or *Conduit*).
1171−The API of a streaming endpoint needs to explicitly specify which sort of
1172−generator it produces. Note that the generator itself is returned by a
1173−`Handler` action, so that additional IO may be done in the creation of one.
1176−type StreamAPI = "userStream" :> StreamGet NewlineFraming JSON (SourceIO User)
1177−streamAPI :: Proxy StreamAPI
1180−streamUsers :: SourceIO User
1181−streamUsers = source [isaac, albert, albert]
1184−app6 = serve streamAPI (return streamUsers)
1187−This simple application returns a stream of `User` values encoded in JSON
1188−format, with each value separated by a newline. In this case, the stream will
1189−consist of the value of `isaac`, followed by the value of `albert`, then the
1190−value of `albert` a second time. Importantly, the stream is written back as
1191−results are produced, rather than all at once. This means first that results
1192−are delivered when they are available, and second, that if an exception
1193−interrupts production of the full stream, nonetheless partial results have
1194−already been written back.
1196## Conclusion
1223## Conclusion
1198−You're now equipped to write webservices/web-applications using
1225+You're now equipped to write any kind of webservice/web-application using
1226+*servant*. One thing not covered here is how to incorporate your own
1227+combinators and will be the topic of a page on the website. The rest of this
1199−**servant**. The rest of this document focuses on **servant-client**,
1228+document focuses on *servant-client*, *servant-jquery* and *servant-docs*.
1200−**servant-js** and **servant-docs**.