git.iko.soy/typeable/servant
on bench help sign in
103 lines 2.9 kB history raw
1# servant-docs
3![servant](https://raw.githubusercontent.com/haskell-servant/servant/master/servant.png)
5Generate API docs for your _servant_ webservice. Feel free to also take a look at [servant-pandoc](https://github.com/mpickering/servant-pandoc) which uses this package to target a broad range of output formats using the excellent **pandoc**.
7## Example
9See [here](https://github.com/haskell-servant/servant/blob/master/servant-docs/example/greet.md) for the output of the following program.
11```haskell
12{-# LANGUAGE DataKinds #-}
13{-# LANGUAGE DeriveGeneric #-}
14{-# LANGUAGE FlexibleInstances #-}
15{-# LANGUAGE MultiParamTypeClasses #-}
16{-# LANGUAGE OverloadedStrings #-}
17{-# LANGUAGE PolyKinds #-}
18{-# LANGUAGE TypeFamilies #-}
19{-# LANGUAGE TypeOperators #-}
21import Data.Aeson (FromJSON, ToJSON)
22import Data.Proxy (Proxy (..))
23import Data.String.Conversions (cs)
24import Data.Text (Text)
25import GHC.Generics (Generic)
26import Servant.API
27 ( (:<|>),
28 (:>),
29 Capture,
30 Delete,
31 Get,
32 JSON,
33 MimeRender,
34 PlainText,
35 Post,
36 QueryParam,
37 ReqBody,
38 mimeRender,
39 )
40import Servant.Docs
41 ( API,
42 DocCapture (..),
43 DocQueryParam (..),
44 ParamKind (..),
45 ToCapture,
46 ToParam,
47 ToSample,
48 docs,
49 markdown,
50 singleSample,
51 toCapture,
52 toParam,
53 toSamples,
54 )
56-- our type for a Greeting message
57data Greet = Greet { _msg :: Text }
58 deriving (Generic, Show)
60-- we get our JSON serialization for free. This will be used by the default
61-- 'MimeRender' instance for 'JSON'.
62instance FromJSON Greet
63instance ToJSON Greet
64instance ToSample ()
66-- We can also implement 'MimeRender' explicitly for additional formats.
67instance MimeRender PlainText Greet where
68 mimeRender Proxy (Greet s) = "<h1>" <> cs s <> "</h1>"
70-- we provide a sample value for the 'Greet' type
71instance ToSample Greet where
72 toSamples _ = singleSample g
73 where g = Greet "Hello, haskeller!"
75instance ToParam (QueryParam "capital" Bool) where
76 toParam _ =
77 DocQueryParam "capital"
78 ["true", "false"]
79 "Get the greeting message in uppercase (true) or not (false). Default is false."
80 Normal
82instance ToCapture (Capture "name" Text) where
83 toCapture _ = DocCapture "name" "name of the person to greet"
85instance ToCapture (Capture "greetid" Text) where
86 toCapture _ = DocCapture "greetid" "identifier of the greet msg to remove"
88-- API specification
89type TestApi =
90 "hello" :> Capture "name" Text :> QueryParam "capital" Bool :> Get '[JSON,PlainText] Greet
91 :<|> "greet" :> ReqBody '[JSON] Greet :> Post '[JSON] Greet
92 :<|> "delete" :> Capture "greetid" Text :> Delete '[JSON] ()
94testApi :: Proxy TestApi
95testApi = Proxy
97-- Generate the Documentation's ADT
98greetDocs :: API
99greetDocs = docs testApi
101main :: IO ()
102main = putStrLn $ markdown greetDocs
103```