2title: Generating documentation from API types
6The source for this tutorial section is a literate haskell file, so first we
7need to have some language extensions and imports:
9> {-# LANGUAGE DataKinds #-}
10> {-# LANGUAGE DeriveGeneric #-}
11> {-# LANGUAGE FlexibleInstances #-}
12> {-# LANGUAGE MultiParamTypeClasses #-}
13> {-# LANGUAGE OverloadedStrings #-}
14> {-# LANGUAGE TypeOperators #-}
15> {-# OPTIONS_GHC -fno-warn-orphans #-}
19> import Data.ByteString.Lazy (ByteString)
21> import Data.Text.Lazy.Encoding (encodeUtf8)
22> import Data.Text.Lazy (pack)
23> import Network.HTTP.Types
27> import Servant.Server
29And we'll import some things from one of our earlier modules
30([Serving an API](/tutorial/server.html)):
32> import Server (Email(..), ClientInfo(..), Position(..), HelloMessage(..),
33> server3, emailForClient)
35Like client function generation, documentation generation amounts to inspecting the API type and extracting all the data we need to then present it in some format to users of your API.
37This time however, we have to assist *servant*. While it is able to deduce a lot of things about our API, it can't magically come up with descriptions of the various pieces of our APIs that are human-friendly and explain what's going on "at the business-logic level". A good example to study for documentation generation is our webservice with the `/position`, `/hello` and `/marketing` endpoints from earlier:
39> type ExampleAPI = "position" :> Capture "x" Int :> Capture "y" Int :> Get '[JSON] Position
40> :<|> "hello" :> QueryParam "name" String :> Get '[JSON] HelloMessage
41> :<|> "marketing" :> ReqBody '[JSON] ClientInfo :> Post '[JSON] Email
43> exampleAPI :: Proxy ExampleAPI
46While *servant* can see e.g. that there are 3 endpoints and that the response bodies will be in JSON, it doesn't know what influence the captures, parameters, request bodies and other combinators have on the webservice. This is where some manual work is required.
48For every capture, request body, response body, query param, we have to give some explanations about how it influences the response, what values are possible and the likes. Here's how it looks like for the parameters we have above.
50> instance ToCapture (Capture "x" Int) where
52> DocCapture "x" -- name
53> "(integer) position on the x axis" -- description
55> instance ToCapture (Capture "y" Int) where
57> DocCapture "y" -- name
58> "(integer) position on the y axis" -- description
60> instance ToSample Position Position where
61> toSample _ = Just (Position 3 14) -- example of output
63> instance ToParam (QueryParam "name" String) where
65> DocQueryParam "name" -- name
66> ["Alp", "John Doe", "..."] -- example of values (not necessarily exhaustive)
67> "Name of the person to say hello to." -- description
68> Normal -- Normal, List or Flag
70> instance ToSample HelloMessage HelloMessage where
72> [ ("When a value is provided for 'name'", HelloMessage "Hello, Alp")
73> , ("When 'name' is not specified", HelloMessage "Hello, anonymous coward")
75> -- mutliple examples to display this time
78> ci = ClientInfo "Alp" "alp@foo.com" 26 ["haskell", "mathematics"]
80> instance ToSample ClientInfo ClientInfo where
83> instance ToSample Email Email where
84> toSample _ = Just (emailForClient ci)
86Types that are used as request or response bodies have to instantiate the `ToSample` typeclass which lets you specify one or more examples of values. `Capture`s and `QueryParam`s have to instantiate their respective `ToCapture` and `ToParam` classes and provide a name and some information about the concrete meaning of that argument, as illustrated in the code above.
88With all of this, we can derive docs for our API.
91> apiDocs = docs exampleAPI
93`API` is a type provided by *servant-docs* that stores all the information one needs about a web API in order to generate documentation in some format. Out of the box, *servant-docs* only provides a pretty documentation printer that outputs [Markdown](http://en.wikipedia.org/wiki/Markdown), but the [servant-pandoc](http://hackage.haskell.org/package/servant-pandoc) package can be used to target many useful formats.
95*servant*'s markdown pretty printer is a function named `markdown`.
98markdown :: API -> String
101That lets us see what our API docs look down in markdown, by looking at `markdown apiDocs`.
106 This is our super webservice's API.
115 - **Values**: *Alp, John Doe, ...*
116 - **Description**: Name of the person to say hello to.
124 - Supported content types are:
128 - When a value is provided for 'name'
134 - When 'name' is not specified
137 {"msg":"Hello, anonymous coward"}
144 - Supported content types are:
148 - Example: `application/json`
151 {"email":"alp@foo.com","interested_in":["haskell","mathematics"],"age":26,"name":"Alp"}
159 - Supported content types are:
163 - Response body as below.
166 {"subject":"Hey Alp, we miss you!","body":"Hi Alp,\n\nSince you've recently turned 26, have you checked out our latest haskell, mathematics products? Give us a visit!","to":"alp@foo.com","from":"great@company.com"}
169 ## GET /position/:x/:y
173 - *x*: (integer) position on the x axis
174 - *y*: (integer) position on the y axis
181 - Supported content types are:
185 - Response body as below.
193However, we can also add one or more introduction sections to the document. We just need to tweak the way we generate `apiDocs`. We will also convert the content to a lazy `ByteString` since this is what *wai* expects for `Raw` endpoints.
195> docsBS :: ByteString
199> $ docsWithIntros [intro] exampleAPI
201> where intro = DocIntro "Welcome" ["This is our super webservice's API.", "Enjoy!"]
203`docsWithIntros` just takes an additional parameter, a list of `DocIntro`s that must be displayed before any endpoint docs.
205We can now serve the API *and* the API docs with a simple server.
207> type DocsAPI = ExampleAPI :<|> Raw
209> api :: Proxy DocsAPI
212> server :: Server DocsAPI
213> server = Server.server3 :<|> serveDocs
215> where serveDocs _ respond =
216> respond $ responseLBS ok200 [plain] docsBS
218> plain = ("Content-Type", "text/plain")
221> app = serve api server
223And if you spin up this server with `dist/build/tutorial/tutorial 10` and go to anywhere else than `/position`, `/hello` and `/marketing`, you will see the API docs in markdown. This is because `serveDocs` is attempted if the 3 other endpoints don't match and systematically succeeds since its definition is to just return some fixed bytestring with the `text/plain` content type.
225<div style="text-align: center;">
226 <a href="/tutorial/javascript.html">Previous page: Generating javascript functions to query an API</a>
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list