@@ -18,6 +18,7 @@ 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 #-}
21{-# LANGUAGE ScopedTypeVariables #-}
22{-# LANGUAGE ScopedTypeVariables #-}
22{-# LANGUAGE TypeOperators #-}
23{-# LANGUAGE TypeOperators #-}
@@ -28,7 +29,7 @@ import Prelude.Compat
29import Control.Monad.Except
30import Control.Monad.Except
30import Control.Monad.Reader
31import Control.Monad.Reader
31−import Data.Aeson.Compat
32+import Data.Aeson
32import Data.Aeson.Types
33import Data.Aeson.Types
33import Data.Attoparsec.ByteString
34import Data.Attoparsec.ByteString
34import Data.ByteString (ByteString)
35import Data.ByteString (ByteString)
@@ -45,6 +46,7 @@ import Servant
45import System.Directory
46import System.Directory
46import Text.Blaze
47import Text.Blaze
47import Text.Blaze.Html.Renderer.Utf8
48import Text.Blaze.Html.Renderer.Utf8
49+import Servant.Types.SourceT (source)
48import qualified Data.Aeson.Parser
50import qualified Data.Aeson.Parser
49import qualified Text.Blaze.Html
51import qualified Text.Blaze.Html
@@ -94,12 +96,6 @@ users1 =
97−Let's also write our API type.
100−type UserAPI1 = "users" :> Get '[JSON] [User]
103We can now take care of writing the actual webservice that will handle requests
99We can now take care of writing the actual webservice that will handle requests
104to such an API. This one will be very simple, being reduced to just a single
100to such an API. This one will be very simple, being reduced to just a single
105endpoint. The type of the web application is determined by the API type,
101endpoint. The type of the web application is determined by the API type,
@@ -111,11 +107,11 @@ corresponding API type.
111The first thing to know about the `Server` type family is that behind the
107The first thing to know about the `Server` type family is that behind the
112scenes it will drive the routing, letting you focus only on the business
108scenes it will drive the routing, letting you focus only on the business
113logic. The second thing to know is that for each endpoint, your handlers will
109logic. The second thing to know is that for each endpoint, your handlers will
114−by default run in the `ExceptT ServantErr IO` monad. This is overridable very
110+by default run in the `Handler` monad. This is overridable very
115easily, as explained near the end of this guide. Third thing, the type of the
111easily, as explained near the end of this guide. Third thing, the type of the
116value returned in that monad must be the same as the second argument of the
112value returned in that monad must be the same as the second argument of the
117HTTP method combinator used for the corresponding endpoint. In our case, it
113HTTP method combinator used for the corresponding endpoint. In our case, it
118−means we must provide a handler of type `ExceptT ServantErr IO [User]`. Well,
114+means we must provide a handler of type `Handler [User]`. Well,
119we have a monad, let's just `return` our list:
115we have a monad, let's just `return` our list:
121``` haskell
117``` haskell
@@ -187,7 +183,7 @@ users2 = [isaac, albert]
188Now, just like we separate the various endpoints in `UserAPI` with `:<|>`, we
184Now, just like we separate the various endpoints in `UserAPI` with `:<|>`, we
189are going to separate the handlers with `:<|>` too! They must be provided in
185are going to separate the handlers with `:<|>` too! They must be provided in
190−the same order as in in the API type.
186+the same order as in the API type.
192``` haskell
188``` haskell
193server2 :: Server UserAPI2
189server2 :: Server UserAPI2
@@ -203,7 +199,7 @@ And that's it! You can run this example in the same way that we showed for
204Fine, we can write trivial webservices easily, but none of the two above use
200Fine, we can write trivial webservices easily, but none of the two above use
205any "fancy" combinator from servant. Let's address this and use `QueryParam`,
201any "fancy" combinator from servant. Let's address this and use `QueryParam`,
206−`Capture` and `ReqBody` right away. You'll see how each occurence of these
202+`Capture` and `ReqBody` right away. You'll see how each occurrence of these
207combinators in an endpoint makes the corresponding handler receive an
203combinators in an endpoint makes the corresponding handler receive an
208argument of the appropriate type automatically. You don't have to worry about
204argument of the appropriate type automatically. You don't have to worry about
209manually looking up URL captures or query string parameters, or
205manually looking up URL captures or query string parameters, or
@@ -269,15 +265,15 @@ server3 = position
269 :<|> hello
265 :<|> hello
270 :<|> marketing
266 :<|> marketing
272− where position :: Int -> Int -> ExceptT ServantErr IO Position
268+ where position :: Int -> Int -> Handler Position
273 position x y = return (Position x y)
269 position x y = return (Position x y)
275− hello :: Maybe String -> ExceptT ServantErr IO HelloMessage
271+ hello :: Maybe String -> Handler HelloMessage
276 hello mname = return . HelloMessage $ case mname of
272 hello mname = return . HelloMessage $ case mname of
277 Nothing -> "Hello, anonymous coward"
273 Nothing -> "Hello, anonymous coward"
278 Just n -> "Hello, " ++ n
274 Just n -> "Hello, " ++ n
280− marketing :: ClientInfo -> ExceptT ServantErr IO Email
276+ marketing :: ClientInfo -> Handler Email
281 marketing clientinfo = return (emailForClient clientinfo)
277 marketing clientinfo = return (emailForClient clientinfo)
@@ -307,7 +303,7 @@ $ curl -X POST -d '{"clientName":"Alp Mestanogullari", "clientEmail" : "alp@foo.
308For reference, here's a list of some combinators from **servant**:
304For reference, here's a list of some combinators from **servant**:
310− > - `Delete`, `Get`, `Patch`, `Post`, `Put`: these do not become arguments. They provide the return type of handlers, which usually is `ExceptT ServantErr IO <something>`.
306+ > - `Delete`, `Get`, `Patch`, `Post`, `Put`: these do not become arguments. They provide the return type of handlers, which usually is `Handler <something>`.
311 > - `Capture "something" a` becomes an argument of type `a`.
307 > - `Capture "something" a` becomes an argument of type `a`.
312 > - `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.
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.
313 > - `QueryFlag "something"` gets turned into an argument of type `Bool`.
309 > - `QueryFlag "something"` gets turned into an argument of type `Bool`.
@@ -317,8 +313,8 @@ For reference, here's a list of some combinators from **servant**:
317## The `FromHttpApiData`/`ToHttpApiData` classes
313## The `FromHttpApiData`/`ToHttpApiData` classes
319Wait... How does **servant** know how to decode the `Int`s from the URL? Or how
315Wait... How does **servant** know how to decode the `Int`s from the URL? Or how
320−to decode a `ClientInfo` value from the request body? This is what this and the
316+to decode a `ClientInfo` value from the request body? The following three sections will
321−following two sections address.
317+help us answer these questions.
323`Capture`s and `QueryParam`s are represented by some textual value in URLs.
319`Capture`s and `QueryParam`s are represented by some textual value in URLs.
324`Header`s are similarly represented by a pair of a header name and a
320`Header`s are similarly represented by a pair of a header name and a
@@ -601,10 +597,9 @@ $ curl -H 'Accept: text/html' http://localhost:8081/persons
601# or just point your browser to http://localhost:8081/persons
597# or just point your browser to http://localhost:8081/persons
604−## The `ExceptT ServantErr IO` monad
600+## The `Handler` monad
606−At the heart of the handlers is the monad they run in, namely `ExceptT
602+At the heart of the handlers is the monad they run in, namely a newtype `Handler` around `ExceptT ServerError IO`
608([haddock documentation for `ExceptT`](http://hackage.haskell.org/package/mtl-2.2.1/docs/Control-Monad-Except.html#t:ExceptT)).
603([haddock documentation for `ExceptT`](http://hackage.haskell.org/package/mtl-2.2.1/docs/Control-Monad-Except.html#t:ExceptT)).
609One might wonder: why this monad? The answer is that it is the
604One might wonder: why this monad? The answer is that it is the
610simplest monad with the following properties:
605simplest monad with the following properties:
@@ -621,13 +616,13 @@ Let's recall some definitions.
621newtype ExceptT e m a = ExceptT (m (Either e a))
616newtype ExceptT e m a = ExceptT (m (Either e a))
624−In short, this means that a handler of type `ExceptT ServantErr IO a` is simply
619+In short, this means that a handler of type `Handler a` is simply
625−equivalent to a computation of type `IO (Either ServantErr a)`, that is, an IO
620+equivalent to a computation of type `IO (Either ServerError a)`, that is, an IO
626action that either returns an error or a result.
621action that either returns an error or a result.
628−The module [`Control.Monad.Except`](https://hackage.haskell.org/package/mtl-2.2.1/docs/Control-Monad-Except.html#t:ExceptT)
623+The module [`Control.Monad.Except`](https://hackage.haskell.org/package/mtl/docs/Control-Monad-Except.html#t:ExceptT)
629from which `ExceptT` comes is worth looking at.
624from which `ExceptT` comes is worth looking at.
630−Perhaps most importantly, `ExceptT` is an instance of `MonadError`, so
625+Perhaps most importantly, `ExceptT` and `Handler` are instances of `MonadError`, so
631`throwError` can be used to return an error from your handler (whereas `return`
626`throwError` can be used to return an error from your handler (whereas `return`
632 is enough to return a success).
627 is enough to return a success).
@@ -637,9 +632,9 @@ kind and abort early. The next two sections cover how to do just that.
638### Performing IO
633### Performing IO
640−Another important instance from the list above is `MonadIO m => MonadIO
635+Other important instances from the list above are `MonadIO m => MonadIO
641−(ExceptT e m)`.
636+(ExceptT e m)`, and therefore also `MonadIO Handler` as there is a `MonadIO IO` instance.
642−[`MonadIO`](http://hackage.haskell.org/package/transformers-0.4.3.0/docs/Control-Monad-IO-Class.html)
637+[`MonadIO`](http://hackage.haskell.org/package/base/docs/Control-Monad-IO-Class.html#t:MonadIO)
643is a class from the **transformers** package defined as:
638is a class from the **transformers** package defined as:
645``` haskell ignore
640``` haskell ignore
@@ -647,8 +642,7 @@ class Monad m => MonadIO m where
647 liftIO :: IO a -> m a
642 liftIO :: IO a -> m a
650−The `IO` monad provides a `MonadIO` instance. Hence for any type
651−`e`, `ExceptT e IO` has a `MonadIO` instance. So if you want to run any kind of
645+So if you want to run any kind of
652IO computation in your handlers, just use `liftIO`:
646IO computation in your handlers, just use `liftIO`:
654``` haskell
648``` haskell
@@ -666,16 +660,16 @@ server5 = do
666 return (FileContent filecontent)
660 return (FileContent filecontent)
669−### Failing, through `ServantErr`
663+### Failing, through `ServerError`
671If you want to explicitly fail at providing the result promised by an endpoint
665If you want to explicitly fail at providing the result promised by an endpoint
672using the appropriate HTTP status code (not found, unauthorized, etc) and some
666using the appropriate HTTP status code (not found, unauthorized, etc) and some
673error message, all you have to do is use the `throwError` function mentioned above
667error message, all you have to do is use the `throwError` function mentioned above
674−and provide it with the appropriate value of type `ServantErr`, which is
668+and provide it with the appropriate value of type `ServerError`, which is
675defined as:
669defined as:
677``` haskell ignore
671``` haskell ignore
678−data ServantErr = ServantErr
672+data ServerError = ServerError
679 { errHTTPCode :: Int
673 { errHTTPCode :: Int
680 , errReasonPhrase :: String
674 , errReasonPhrase :: String
681 , errBody :: ByteString -- lazy bytestring
675 , errBody :: ByteString -- lazy bytestring
@@ -688,10 +682,10 @@ module. If you want to use these values but add a body or some headers, just
688use record update syntax:
682use record update syntax:
690``` haskell
684``` haskell
691−failingHandler :: ExceptT ServantErr IO ()
685+failingHandler :: Handler ()
692failingHandler = throwError myerr
686failingHandler = throwError myerr
694− where myerr :: ServantErr
688+ where myerr :: ServerError
695 myerr = err503 { errBody = "Sorry dear user." }
689 myerr = err503 { errBody = "Sorry dear user." }
@@ -722,7 +716,7 @@ $ curl --verbose http://localhost:8081/myfile.txt
723< HTTP/1.1 404 Not Found
717< HTTP/1.1 404 Not Found
725−myfile.txt just isnt there, please leave this server alone.
719+myfile.txt just isn't there, please leave this server alone.
727$ echo Hello > myfile.txt
721$ echo Hello > myfile.txt
@@ -754,7 +748,29 @@ myHandler :: Server MyHandler
754myHandler = return $ addHeader 1797 albert
748myHandler = return $ addHeader 1797 albert
757−Note that the type of `addHeader x` is different than the type of `x`!
751+Note that the type of `addHeader header 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
759## Serving static files
775## Serving static files
@@ -766,10 +782,10 @@ directory serving WAI application, namely:
767``` haskell ignore
783``` haskell ignore
768-- exported by Servant and Servant.Server
784-- exported by Servant and Servant.Server
769−serveDirectory :: FilePath -> Server Raw
785+serveDirectoryWebApp :: FilePath -> Server Raw
772−`serveDirectory`'s argument must be a path to a valid directory.
788+`serveDirectoryWebApp`'s argument must be a path to a valid directory.
774Here's an example API that will serve some static files:
790Here's an example API that will serve some static files:
@@ -786,7 +802,7 @@ staticAPI = Proxy
787``` haskell
803``` haskell
788server7 :: Server StaticAPI
804server7 :: Server StaticAPI
789−server7 = serveDirectory "static-files"
805+server7 = serveDirectoryWebApp "static-files"
791app3 :: Application
807app3 :: Application
792app3 = serve staticAPI server7
808app3 = serve staticAPI server7
@@ -800,6 +816,10 @@ In other words: If a client requests `/static/foo.txt`, the server will look for
800`./static-files/foo.txt`. If that file exists it'll succeed and serve the file.
816`./static-files/foo.txt`. If that file exists it'll succeed and serve the file.
801If it doesn't exist, the handler will fail with a `404` status code.
817If it doesn't exist, the handler will fail with a `404` status code.
819+`serveDirectoryWebApp` uses some standard settings that fit the use case of
820+serving static files for most web apps. You can find out about the other
821+options in the documentation of the `Servant.Server.StaticFiles` module.
803## Nested APIs
823## Nested APIs
805Let's see how you can define APIs in a modular way, while avoiding repetition.
825Let's see how you can define APIs in a modular way, while avoiding repetition.
@@ -810,7 +830,7 @@ type UserAPI3 = -- view the user with given userid, in JSON
810 Capture "userid" Int :> Get '[JSON] User
830 Capture "userid" Int :> Get '[JSON] User
812 :<|> -- delete the user with given userid. empty response
832 :<|> -- delete the user with given userid. empty response
813− Capture "userid" Int :> Delete '[] ()
833+ Capture "userid" Int :> DeleteNoContent
816We can instead factor out the `userid`:
836We can instead factor out the `userid`:
@@ -818,7 +838,7 @@ We can instead factor out the `userid`:
818``` haskell
838``` haskell
819type UserAPI4 = Capture "userid" Int :>
839type UserAPI4 = Capture "userid" Int :>
820 ( Get '[JSON] User
840 ( Get '[JSON] User
821− :<|> Delete '[] ()
841+ :<|> DeleteNoContent
@@ -826,26 +846,26 @@ However, you have to be aware that this has an effect on the type of the
826corresponding `Server`:
846corresponding `Server`:
828``` haskell ignore
848``` haskell ignore
829−Server UserAPI3 = (Int -> ExceptT ServantErr IO User)
849+Server UserAPI3 = (Int -> Handler User)
830− :<|> (Int -> ExceptT ServantErr IO ())
850+ :<|> (Int -> Handler NoContent)
832−Server UserAPI4 = Int -> ( ExceptT ServantErr IO User
852+Server UserAPI4 = Int -> ( Handler User
833− :<|> ExceptT ServantErr IO ()
853+ :<|> Handler NoContent
837In the first case, each handler receives the *userid* argument. In the latter,
857In the first case, each handler receives the *userid* argument. In the latter,
838the whole `Server` takes the *userid* and has handlers that are just
858the whole `Server` takes the *userid* and has handlers that are just
839−computations in `ExceptT`, with no arguments. In other words:
859+computations in `Handler`, with no arguments. In other words:
841``` haskell
861``` haskell
842server8 :: Server UserAPI3
862server8 :: Server UserAPI3
843server8 = getUser :<|> deleteUser
863server8 = getUser :<|> deleteUser
845− where getUser :: Int -> ExceptT ServantErr IO User
865+ where getUser :: Int -> Handler User
846 getUser _userid = error "..."
866 getUser _userid = error "..."
848− deleteUser :: Int -> ExceptT ServantErr IO ()
868+ deleteUser :: Int -> Handler NoContent
849 deleteUser _userid = error "..."
869 deleteUser _userid = error "..."
851-- notice how getUser and deleteUser
871-- notice how getUser and deleteUser
@@ -854,10 +874,10 @@ server8 = getUser :<|> deleteUser
854server9 :: Server UserAPI4
874server9 :: Server UserAPI4
855server9 userid = getUser userid :<|> deleteUser userid
875server9 userid = getUser userid :<|> deleteUser userid
857− where getUser :: Int -> ExceptT ServantErr IO User
877+ where getUser :: Int -> Handler User
858 getUser = error "..."
878 getUser = error "..."
860− deleteUser :: Int -> ExceptT ServantErr IO ()
880+ deleteUser :: Int -> Handler NoContent
861 deleteUser = error "..."
881 deleteUser = error "..."
@@ -876,13 +896,13 @@ type API1 = "users" :>
876-- we factor out the Request Body
896-- we factor out the Request Body
877type API2 = ReqBody '[JSON] User :>
897type API2 = ReqBody '[JSON] User :>
878 ( Get '[JSON] User -- just display the same user back, don't register it
898 ( Get '[JSON] User -- just display the same user back, don't register it
879− :<|> Post '[JSON] () -- register the user. empty response
899+ :<|> PostNoContent -- register the user. empty response
882-- we factor out a Header
902-- we factor out a Header
883type API3 = Header "Authorization" Token :>
903type API3 = Header "Authorization" Token :>
884 ( Get '[JSON] SecretData -- get some secret data, if authorized
904 ( Get '[JSON] SecretData -- get some secret data, if authorized
885− :<|> ReqBody '[JSON] SecretData :> Post '[] () -- add some secret data, if authorized
905+ :<|> ReqBody '[JSON] SecretData :> PostNoContent -- add some secret data, if authorized
888newtype Token = Token ByteString
908newtype Token = Token ByteString
@@ -895,44 +915,44 @@ API type only at the end.
895``` haskell
915``` haskell
896type UsersAPI =
916type UsersAPI =
897 Get '[JSON] [User] -- list users
917 Get '[JSON] [User] -- list users
898− :<|> ReqBody '[JSON] User :> Post '[] () -- add a user
918+ :<|> ReqBody '[JSON] User :> PostNoContent -- add a user
899 :<|> Capture "userid" Int :>
919 :<|> Capture "userid" Int :>
900 ( Get '[JSON] User -- view a user
920 ( Get '[JSON] User -- view a user
901− :<|> ReqBody '[JSON] User :> Put '[] () -- update a user
921+ :<|> ReqBody '[JSON] User :> PutNoContent -- update a user
902− :<|> Delete '[] () -- delete a user
922+ :<|> DeleteNoContent -- delete a user
905usersServer :: Server UsersAPI
925usersServer :: Server UsersAPI
906usersServer = getUsers :<|> newUser :<|> userOperations
926usersServer = getUsers :<|> newUser :<|> userOperations
908− where getUsers :: ExceptT ServantErr IO [User]
928+ where getUsers :: Handler [User]
909 getUsers = error "..."
929 getUsers = error "..."
911− newUser :: User -> ExceptT ServantErr IO ()
931+ newUser :: User -> Handler NoContent
912 newUser = error "..."
932 newUser = error "..."
914 userOperations userid =
934 userOperations userid =
915 viewUser userid :<|> updateUser userid :<|> deleteUser userid
935 viewUser userid :<|> updateUser userid :<|> deleteUser userid
918− viewUser :: Int -> ExceptT ServantErr IO User
938+ viewUser :: Int -> Handler User
919 viewUser = error "..."
939 viewUser = error "..."
921− updateUser :: Int -> User -> ExceptT ServantErr IO ()
941+ updateUser :: Int -> User -> Handler NoContent
922 updateUser = error "..."
942 updateUser = error "..."
924− deleteUser :: Int -> ExceptT ServantErr IO ()
944+ deleteUser :: Int -> Handler NoContent
925 deleteUser = error "..."
945 deleteUser = error "..."
928``` haskell
948``` haskell
929type ProductsAPI =
949type ProductsAPI =
930 Get '[JSON] [Product] -- list products
950 Get '[JSON] [Product] -- list products
931− :<|> ReqBody '[JSON] Product :> Post '[] () -- add a product
951+ :<|> ReqBody '[JSON] Product :> PostNoContent -- add a product
932 :<|> Capture "productid" Int :>
952 :<|> Capture "productid" Int :>
933 ( Get '[JSON] Product -- view a product
953 ( Get '[JSON] Product -- view a product
934− :<|> ReqBody '[JSON] Product :> Put '[] () -- update a product
954+ :<|> ReqBody '[JSON] Product :> PutNoContent -- update a product
935− :<|> Delete '[] () -- delete a product
955+ :<|> DeleteNoContent -- delete a product
938data Product = Product { productId :: Int }
958data Product = Product { productId :: Int }
@@ -940,23 +960,23 @@ data Product = Product { productId :: Int }
940productsServer :: Server ProductsAPI
960productsServer :: Server ProductsAPI
941productsServer = getProducts :<|> newProduct :<|> productOperations
961productsServer = getProducts :<|> newProduct :<|> productOperations
943− where getProducts :: ExceptT ServantErr IO [Product]
963+ where getProducts :: Handler [Product]
944 getProducts = error "..."
964 getProducts = error "..."
946− newProduct :: Product -> ExceptT ServantErr IO ()
966+ newProduct :: Product -> Handler NoContent
947 newProduct = error "..."
967 newProduct = error "..."
949 productOperations productid =
969 productOperations productid =
950 viewProduct productid :<|> updateProduct productid :<|> deleteProduct productid
970 viewProduct productid :<|> updateProduct productid :<|> deleteProduct productid
953− viewProduct :: Int -> ExceptT ServantErr IO Product
973+ viewProduct :: Int -> Handler Product
954 viewProduct = error "..."
974 viewProduct = error "..."
956− updateProduct :: Int -> Product -> ExceptT ServantErr IO ()
976+ updateProduct :: Int -> Product -> Handler NoContent
957 updateProduct = error "..."
977 updateProduct = error "..."
959− deleteProduct :: Int -> ExceptT ServantErr IO ()
979+ deleteProduct :: Int -> Handler NoContent
960 deleteProduct = error "..."
980 deleteProduct = error "..."
@@ -976,34 +996,44 @@ abstract that away:
976-- indexed by values of type 'i'
996-- indexed by values of type 'i'
977type APIFor a i =
997type APIFor a i =
978 Get '[JSON] [a] -- list 'a's
998 Get '[JSON] [a] -- list 'a's
979− :<|> ReqBody '[JSON] a :> Post '[] () -- add an 'a'
999+ :<|> ReqBody '[JSON] a :> PostNoContent -- add an 'a'
980 :<|> Capture "id" i :>
1000 :<|> Capture "id" i :>
981 ( Get '[JSON] a -- view an 'a' given its "identifier" of type 'i'
1001 ( Get '[JSON] a -- view an 'a' given its "identifier" of type 'i'
982− :<|> ReqBody '[JSON] a :> Put '[] () -- update an 'a'
1002+ :<|> ReqBody '[JSON] a :> PutNoContent -- update an 'a'
983− :<|> Delete '[] () -- delete an 'a'
1003+ :<|> DeleteNoContent -- delete an 'a'
986-- Build the appropriate 'Server'
1006-- Build the appropriate 'Server'
987-- given the handlers of the right type.
1007-- given the handlers of the right type.
988−serverFor :: ExceptT ServantErr IO [a] -- handler for listing of 'a's
1008+serverFor :: Handler [a] -- handler for listing of 'a's
989− -> (a -> ExceptT ServantErr IO ()) -- handler for adding an 'a'
1009+ -> (a -> Handler NoContent) -- handler for adding an 'a'
990− -> (i -> ExceptT ServantErr IO a) -- handler for viewing an 'a' given its identifier of type 'i'
1010+ -> (i -> Handler a) -- handler for viewing an 'a' given its identifier of type 'i'
991− -> (i -> a -> ExceptT ServantErr IO ()) -- updating an 'a' with given id
1011+ -> (i -> a -> Handler NoContent) -- updating an 'a' with given id
992− -> (i -> ExceptT ServantErr IO ()) -- deleting an 'a' given its id
1012+ -> (i -> Handler NoContent) -- deleting an 'a' given its id
993 -> Server (APIFor a i)
1013 -> Server (APIFor a i)
994serverFor = error "..."
1014serverFor = error "..."
995-- implementation left as an exercise. contact us on IRC
1015-- implementation left as an exercise. contact us on IRC
996-- or the mailing list if you get stuck!
1016-- 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
999## Using another monad for your handlers
1030## Using another monad for your handlers
1001−Remember how `Server` turns combinators for HTTP methods into `ExceptT
1032+Remember how `Server` turns combinators for HTTP methods into `Handler`? Well, actually, there's more to that. `Server` is actually a
1002−ServantErr IO`? Well, actually, there's more to that. `Server` is actually a
1003simple type synonym.
1033simple type synonym.
1005``` haskell ignore
1035``` haskell ignore
1006−type Server api = ServerT api (ExceptT ServantErr IO)
1036+type Server api = ServerT api Handler
1009`ServerT` is the actual type family that computes the required types for the
1039`ServerT` is the actual type family that computes the required types for the
@@ -1023,77 +1053,71 @@ into something **servant** can understand?
1023If we have a function that gets us from an `m a` to an `n a`, for any `a`, what
1053If we have a function that gets us from an `m a` to an `n a`, for any `a`, what
1024do we have?
1054do we have?
1026−``` haskell ignore
1056+``` haskell
1027−newtype m :~> n = Nat { unNat :: forall a. m a -> n a}
1057+type (~>) m n = forall a. m a -> n a
1030For example:
1060For example:
1032``` haskell
1062``` haskell
1033−listToMaybeNat :: [] :~> Maybe
1063+listToMaybe' :: [] ~> Maybe
1034−listToMaybeNat = Nat listToMaybe -- from Data.Maybe
1064+listToMaybe' = listToMaybe -- from Data.Maybe
1037−(`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.
1039−So if you want to write handlers using another monad/type than `ExceptT
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
1040−ServantErr IO`, say the `Reader String` monad, the first thing you have to
1041prepare is a function:
1071prepare is a function:
1043``` haskell ignore
1073``` haskell ignore
1044−readerToHandler :: Reader String :~> ExceptT ServantErr IO
1074+readerToHandler :: Reader String a -> Handler a
1047−Let's start with `readerToHandler'`. We obviously have to run the `Reader`
1048−computation by supplying it with a `String`, like `"hi"`. We get an `a` out
1077+We obviously have to run the `Reader` computation by supplying it with a
1049−from that and can then just `return` it into `ExceptT`. We can then just wrap
1078+`String`, like `"hi"`. We get an `a` out from that and can then just `return`
1050−that function with the `Nat` constructor to make it have the fancier type.
1079+it into `Handler`.
1052``` haskell
1081``` haskell
1053−readerToHandler' :: forall a. Reader String a -> ExceptT ServantErr IO a
1082+readerToHandler :: Reader String a -> Handler a
1054−readerToHandler' r = return (runReader r "hi")
1083+readerToHandler r = return (runReader r "hi")
1056−readerToHandler :: Reader String :~> ExceptT ServantErr IO
1057−readerToHandler = Nat readerToHandler'
1060We can write some simple webservice with the handlers running in `Reader String`.
1086We can write some simple webservice with the handlers running in `Reader String`.
1062``` haskell
1088``` haskell
1063type ReaderAPI = "a" :> Get '[JSON] Int
1089type ReaderAPI = "a" :> Get '[JSON] Int
1064− :<|> "b" :> Get '[JSON] String
1090+ :<|> "b" :> ReqBody '[JSON] Double :> Get '[JSON] Bool
1066readerAPI :: Proxy ReaderAPI
1092readerAPI :: Proxy ReaderAPI
1067readerAPI = Proxy
1093readerAPI = Proxy
1069readerServerT :: ServerT ReaderAPI (Reader String)
1095readerServerT :: ServerT ReaderAPI (Reader String)
1070−readerServerT = a :<|> b
1096+readerServerT = a :<|> b where
1072− where a :: Reader String Int
1097+ a :: Reader String Int
1073− a = return 1797
1098+ a = return 1797
1075− b :: Reader String String
1100+ b :: Double -> Reader String Bool
1076− b = ask
1101+ b _ = asks (== "hi")
1079We unfortunately can't use `readerServerT` as an argument of `serve`, because
1104We unfortunately can't use `readerServerT` as an argument of `serve`, because
1080−`serve` wants a `Server ReaderAPI`, i.e., with handlers running in `ExceptT
1105+`serve` wants a `Server ReaderAPI`, i.e., with handlers running in `Handler`. But there's a simple solution to this.
1081−ServantErr IO`. But there's a simple solution to this.
1083−### Enter `enter`
1107+### Welcome `hoistServer`
1085That's right. We have just written `readerToHandler`, which is exactly what we
1109That's right. We have just written `readerToHandler`, which is exactly what we
1086would need to apply to all handlers to make the handlers have the
1110would need to apply to all handlers to make the handlers have the
1087right type for `serve`. Being cumbersome to do by hand, we provide a function
1111right type for `serve`. Being cumbersome to do by hand, we provide a function
1088−`enter` which takes a natural transformation between two parametrized types `m`
1112+`hoistServer` which takes a natural transformation between two parameterized types `m`
1089and `n` and a `ServerT someapi m`, and returns a `ServerT someapi n`.
1113and `n` and a `ServerT someapi m`, and returns a `ServerT someapi n`.
1091−In our case, we can wrap up our little webservice by using `enter
1115+In our case, we can wrap up our little webservice by using
1092−readerToHandler` on our handlers.
1116+`hoistServer readerAPI readerToHandler` on our handlers.
1094``` haskell
1118``` haskell
1095readerServer :: Server ReaderAPI
1119readerServer :: Server ReaderAPI
1096−readerServer = enter readerToHandler readerServerT
1120+readerServer = hoistServer readerAPI readerToHandler readerServerT
1098app4 :: Application
1122app4 :: Application
1099app4 = serve readerAPI readerServer
1123app4 = serve readerAPI readerServer
@@ -1104,10 +1128,71 @@ This is the webservice in action:
1105$ curl http://localhost:8081/a
1129$ curl http://localhost:8081/a
1107−$ curl http://localhost:8081/b
1131+$ curl http://localhost:8081/b -X GET -d '42.0' -H 'Content-Type: application/json'
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
1108−"hi"
1153+ b _ s = s == "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.
1111## Conclusion
1196## Conclusion
1113You're now equipped to write webservices/web-applications using
1198You're now equipped to write webservices/web-applications using