servant/doc/tutorial/Docs.lhs

277 lines
9.4 KiB
Text
Raw Permalink Normal View History

2016-02-18 18:13:43 +01:00
# Documenting an API
2016-01-25 14:11:40 +01:00
The source for this tutorial section is a literate haskell file, so first we
need to have some language extensions and imports:
2016-01-27 22:28:58 +01:00
``` haskell
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Docs where
import Data.ByteString.Lazy (ByteString)
import Data.Proxy
import Data.Text.Lazy.Encoding (encodeUtf8)
import Data.Text.Lazy (pack)
import Network.HTTP.Types
import Network.Wai
import Servant.API
import Servant.Docs
import Servant.Server
2017-10-09 04:22:54 +02:00
import Web.FormUrlEncoded(FromForm(..), ToForm(..))
2016-01-27 22:28:58 +01:00
```
2016-01-25 14:11:40 +01:00
And we'll import some things from one of our earlier modules
2016-02-28 22:32:53 +01:00
([Serving an API](Server.html)):
2016-01-25 14:11:40 +01:00
2016-01-27 22:28:58 +01:00
``` haskell
import Server (Email(..), ClientInfo(..), Position(..), HelloMessage(..),
server3, emailForClient)
```
2016-01-25 14:11:40 +01:00
Like 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.
2016-02-28 22:32:53 +01:00
This 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:
2016-01-25 14:11:40 +01:00
2016-01-27 22:28:58 +01:00
``` haskell
2017-05-17 07:50:38 +02:00
type ExampleAPI = "position" :> Capture "x" Int :> Capture "y" Int :> Get '[JSON] Position
2016-01-27 22:28:58 +01:00
:<|> "hello" :> QueryParam "name" String :> Get '[JSON] HelloMessage
2017-05-17 07:50:38 +02:00
:<|> "marketing" :> ReqBody '[JSON] ClientInfo :> Post '[JSON] Email
2016-01-27 22:28:58 +01:00
exampleAPI :: Proxy ExampleAPI
exampleAPI = Proxy
```
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
While **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.
2016-01-25 14:11:40 +01:00
For 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.
2016-01-27 22:28:58 +01:00
``` haskell
instance ToCapture (Capture "x" Int) where
toCapture _ =
DocCapture "x" -- name
"(integer) position on the x axis" -- description
instance ToCapture (Capture "y" Int) where
toCapture _ =
DocCapture "y" -- name
"(integer) position on the y axis" -- description
2016-01-28 15:46:56 +01:00
instance ToSample Position where
toSamples _ = singleSample (Position 3 14) -- example of output
2016-01-27 22:28:58 +01:00
instance ToParam (QueryParam "name" String) where
toParam _ =
DocQueryParam "name" -- name
["Alp", "John Doe", "..."] -- example of values (not necessarily exhaustive)
"Name of the person to say hello to." -- description
Normal -- Normal, List or Flag
2016-01-28 15:46:56 +01:00
instance ToSample HelloMessage where
2016-01-27 22:28:58 +01:00
toSamples _ =
[ ("When a value is provided for 'name'", HelloMessage "Hello, Alp")
, ("When 'name' is not specified", HelloMessage "Hello, anonymous coward")
]
-- mutliple examples to display this time
ci :: ClientInfo
ci = ClientInfo "Alp" "alp@foo.com" 26 ["haskell", "mathematics"]
2016-01-28 15:46:56 +01:00
instance ToSample ClientInfo where
toSamples _ = singleSample ci
2016-01-27 22:28:58 +01:00
2016-01-28 15:46:56 +01:00
instance ToSample Email where
toSamples _ = singleSample (emailForClient ci)
2016-01-27 22:28:58 +01:00
```
2016-01-25 14:11:40 +01:00
Types 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.
2017-05-17 10:24:04 +02:00
The `EmptyAPI` combinator needs no special treatment as it generates no
documentation: an empty API has no endpoints to document.
2016-01-25 14:11:40 +01:00
With all of this, we can derive docs for our API.
2016-01-27 22:28:58 +01:00
``` haskell
apiDocs :: API
apiDocs = docs exampleAPI
```
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
`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.
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
**servant**'s markdown pretty printer is a function named `markdown`.
2016-01-25 14:11:40 +01:00
2016-01-27 22:26:59 +01:00
``` haskell ignore
2016-01-25 14:11:40 +01:00
markdown :: API -> String
```
That lets us see what our API docs look down in markdown, by looking at `markdown apiDocs`.
2016-02-28 22:32:53 +01:00
````````` text
## GET /hello
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
#### GET Parameters:
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
- name
- **Values**: *Alp, John Doe, ...*
- **Description**: Name of the person to say hello to.
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
#### Response:
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
- Status code 200
- Headers: []
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
- Supported content types are:
2016-01-25 14:11:40 +01:00
- `application/json;charset=utf-8`
2016-02-28 22:32:53 +01:00
- `application/json`
2016-01-25 14:11:40 +01:00
- When a value is provided for 'name' (`application/json;charset=utf-8`, `application/json`):
2016-01-25 14:11:40 +01:00
```javascript
{"msg":"Hello, Alp"}
```
2016-01-25 14:11:40 +01:00
- When 'name' is not specified (`application/json;charset=utf-8`, `application/json`):
2016-01-25 14:11:40 +01:00
```javascript
{"msg":"Hello, anonymous coward"}
```
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
## POST /marketing
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
#### Request:
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
- Supported content types are:
2016-01-25 14:11:40 +01:00
- `application/json;charset=utf-8`
2016-02-28 22:32:53 +01:00
- `application/json`
2016-01-25 14:11:40 +01:00
- Example (`application/json;charset=utf-8`, `application/json`):
2016-01-25 14:11:40 +01:00
```javascript
{"clientAge":26,"clientEmail":"alp@foo.com","clientName":"Alp","clientInterestedIn":["haskell","mathematics"]}
```
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
#### Response:
2016-01-25 14:11:40 +01:00
- Status code 200
2016-02-28 22:32:53 +01:00
- Headers: []
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
- Supported content types are:
2016-01-25 14:11:40 +01:00
- `application/json;charset=utf-8`
2016-02-28 22:32:53 +01:00
- `application/json`
2016-01-25 14:11:40 +01:00
- Example (`application/json;charset=utf-8`, `application/json`):
2016-01-25 14:11:40 +01:00
```javascript
{"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"}
```
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
## GET /position/:x/:y
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
#### Captures:
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
- *x*: (integer) position on the x axis
- *y*: (integer) position on the y axis
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
#### Response:
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
- Status code 200
- Headers: []
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
- Supported content types are:
2016-01-25 14:11:40 +01:00
- `application/json;charset=utf-8`
2016-02-28 22:32:53 +01:00
- `application/json`
2016-01-25 14:11:40 +01:00
- Example (`application/json;charset=utf-8`, `application/json`):
2016-01-25 14:11:40 +01:00
```javascript
{"yCoord":14,"xCoord":3}
````
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
`````````
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
However, 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.
2016-01-25 14:11:40 +01:00
2016-01-27 22:28:58 +01:00
``` haskell
docsBS :: ByteString
docsBS = encodeUtf8
. pack
. markdown
$ docsWithIntros [intro] exampleAPI
where intro = DocIntro "Welcome" ["This is our super webservice's API.", "Enjoy!"]
```
2016-01-25 14:11:40 +01:00
`docsWithIntros` just takes an additional parameter, a list of `DocIntro`s that must be displayed before any endpoint docs.
More customisation can be done with the `markdownWith` function, which allows customising some of the parameters used when generating Markdown. The most obvious of these is how to handle when a request or response body has multiple content types. For example, if we make a slight change to the `/marketing` endpoint of our API so that the request body can also be encoded as a form:
``` haskell
type ExampleAPI2 = "position" :> Capture "x" Int :> Capture "y" Int :> Get '[JSON] Position
:<|> "hello" :> QueryParam "name" String :> Get '[JSON] HelloMessage
:<|> "marketing" :> ReqBody '[JSON, FormUrlEncoded] ClientInfo :> Post '[JSON] Email
2017-10-09 04:22:54 +02:00
instance ToForm ClientInfo
instance FromForm ClientInfo
exampleAPI2 :: Proxy ExampleAPI2
exampleAPI2 = Proxy
api2Docs :: API
api2Docs = docs exampleAPI2
```
The relevant output of `markdown api2Docs` is now:
```````` text
#### Request:
- Supported content types are:
- `application/json;charset=utf-8`
- `application/json`
- `application/x-www-form-urlencoded`
- Example (`application/json;charset=utf-8`, `application/json`):
```javascript
{"clientAge":26,"clientEmail":"alp@foo.com","clientName":"Alp","clientInterestedIn":["haskell","mathematics"]}
```
- Example (`application/x-www-form-urlencoded`):
```
clientAge=26&clientEmail=alp%40foo.com&clientName=Alp&clientInterestedIn=haskell&clientInterestedIn=mathematics
```
````````
If, however, you don't want the extra example encoding shown, then you can use `markdownWith (defRenderingOptions & requestExamples .~ FirstContentType)` to get behaviour identical to `markdown apiDocs`.
2016-01-25 14:11:40 +01:00
We can now serve the API *and* the API docs with a simple server.
2016-01-27 22:28:58 +01:00
``` haskell
type DocsAPI = ExampleAPI :<|> Raw
api :: Proxy DocsAPI
api = Proxy
server :: Server DocsAPI
2017-05-17 07:50:38 +02:00
server = Server.server3 :<|> Tagged serveDocs where
serveDocs _ respond =
respond $ responseLBS ok200 [plain] docsBS
plain = ("Content-Type", "text/plain")
2016-01-27 22:28:58 +01:00
app :: Application
2016-02-27 19:53:03 +01:00
app = serve api server
2016-01-27 22:28:58 +01:00
```
2016-01-25 14:11:40 +01:00
2016-02-28 22:32:53 +01:00
And if you spin up this server and request anything 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.