on master help sign in
Merge remote-tracking branch 'servant-docs/prepare-merge' into merge
commit03862836c422a16cefc7adf1f064e78517495586 authorJulian K. Arni <jkarni@gmail.com> dateMon 20 Apr 2015, 11:24 (11 years ago) parent1eedad488f1a3f
14 files changed+1547
servant-docs/CHANGELOG.md+15 servant-docs/LICENSE+30 servant-docs/README.md+72 servant-docs/Setup.hs+2 servant-docs/default.nix+19 servant-docs/docs.sh+52 servant-docs/example/greet.hs+117 servant-docs/example/greet.md+124 servant-docs/servant-docs.cabal+71 servant-docs/shell.nix+9 servant-docs/src/Servant/Docs.hs+168 servant-docs/src/Servant/Docs/Internal.hs+803 servant-docs/test/Servant/DocsSpec.hs+64 servant-docs/test/Spec.hs+1
servant-docs/CHANGELOG.mdnew file+15
@@ -0,0 +1,15 @@
1+0.4
2+---
3+* Allow for extra information to be added to the docs
4+* Support content-type aware combinators of *servant-0.3*
5+* Render endpoints in a canonical order (https://github.com/haskell-servant/servant-docs/pull/15)
6+* Remove ToJSON superclass from ToSample
7+* Split out Internal module
8+* `Canonicalize` API types before generating the docs for them
9+
10+0.3
11+---
12+
13+* Add the ability to display multiple responses, with some accompanying `Text` to describe the context in which we get the corresponding JSON.
14+* Expose the `headers` lens
15+* Represent an endpoint's path as `[String]` (previously `String`), fixing a corner case where the leading `/` would be missing.
servant-docs/LICENSEnew file+30
@@ -0,0 +1,30 @@
1+Copyright (c) 2014, Zalora South East Asia Pte Ltd
2+
3+All rights reserved.
4+
5+Redistribution and use in source and binary forms, with or without
6+modification, are permitted provided that the following conditions are met:
7+
8+ * Redistributions of source code must retain the above copyright
9+ notice, this list of conditions and the following disclaimer.
10+
11+ * Redistributions in binary form must reproduce the above
12+ copyright notice, this list of conditions and the following
13+ disclaimer in the documentation and/or other materials provided
14+ with the distribution.
15+
16+ * Neither the name of Zalora South East Asia Pte Ltd nor the names of other
17+ contributors may be used to endorse or promote products derived
18+ from this software without specific prior written permission.
19+
20+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
servant-docs/README.mdnew file+72
@@ -0,0 +1,72 @@
1+# servant-docs
2+
3+[![Build Status](https://secure.travis-ci.org/haskell-servant/servant-docs.svg)](http://travis-ci.org/haskell-servant/servant-docs)
4+
5+![servant](https://raw.githubusercontent.com/haskell-servant/servant/master/servant.png)
6+
7+Generate 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**.
8+
9+## Example
10+
11+See [here](https://github.com/haskell-servant/servant-docs/blob/master/example/greet.md) for the output of the following program.
12+
13+``` haskell
14+{-# LANGUAGE DataKinds #-}
15+{-# LANGUAGE PolyKinds #-}
16+{-# LANGUAGE TypeFamilies #-}
17+{-# LANGUAGE DeriveGeneric #-}
18+{-# LANGUAGE TypeOperators #-}
19+{-# LANGUAGE FlexibleInstances #-}
20+{-# LANGUAGE OverloadedStrings #-}
21+
22+import Data.Proxy
23+import Data.Text
24+import Servant
25+
26+-- our type for a Greeting message
27+data Greet = Greet { _msg :: Text }
28+ deriving (Generic, Show)
29+
30+-- we get our JSON serialization for free. This will be used by the default
31+-- 'MimeRender' instance for 'JSON'.
32+instance FromJSON Greet
33+instance ToJSON Greet
34+
35+-- We can also implement 'MimeRender' explicitly for additional formats.
36+instance MimeRender PlainText Greet where
37+ toByteString Proxy (Greet s) = "<h1>" <> cs s <> "</h1>"
38+
39+-- we provide a sample value for the 'Greet' type
40+instance ToSample Greet where
41+ toSample = Just g
42+
43+ where g = Greet "Hello, haskeller!"
44+
45+instance ToParam (QueryParam "capital" Bool) where
46+ toParam _ =
47+ DocQueryParam "capital"
48+ ["true", "false"]
49+ "Get the greeting message in uppercase (true) or not (false). Default is false."
50+
51+instance ToCapture (Capture "name" Text) where
52+ toCapture _ = DocCapture "name" "name of the person to greet"
53+
54+instance ToCapture (Capture "greetid" Text) where
55+ toCapture _ = DocCapture "greetid" "identifier of the greet msg to remove"
56+
57+-- API specification
58+type TestApi =
59+ "hello" :> Capture "name" Text :> QueryParam "capital" Bool :> Get '[JSON,PlainText] Greet
60+ :<|> "greet" :> RQBody '[JSON] Greet :> Post '[JSON] Greet
61+ :<|> "delete" :> Capture "greetid" Text :> Delete
62+
63+testApi :: Proxy TestApi
64+testApi = Proxy
65+
66+-- Generate the Documentation's ADT
67+greetDocs :: API
68+greetDocs = docs testApi
69+
70+main :: IO ()
71+main = putStrLn $ markdown greetDocs
72+```
servant-docs/Setup.hsnew file+2
@@ -0,0 +1,2 @@
1+import Distribution.Simple
2+main = defaultMain
servant-docs/default.nixnew file+19
@@ -0,0 +1,19 @@
1+{ mkDerivation, aeson, base, bytestring, hashable, hspec
2+, http-media, lens, servant, stdenv, string-conversions, text
3+, unordered-containers
4+}:
5+mkDerivation {
6+ pname = "servant-docs";
7+ version = "0.3";
8+ src = ./.;
9+ isLibrary = true;
10+ isExecutable = true;
11+ buildDepends = [
12+ aeson base bytestring hashable http-media lens servant
13+ string-conversions text unordered-containers
14+ ];
15+ testDepends = [ aeson base hspec lens servant ];
16+ homepage = "http://haskell-servant.github.io/";
17+ description = "generate API docs for your servant webservice";
18+ license = stdenv.lib.licenses.bsd3;
19+}
servant-docs/docs.shnew file+52
@@ -0,0 +1,52 @@
1+SERVANT_DIR=/tmp/servant-docs-gh-pages
2+
3+# Make a temporary clone
4+
5+rm -rf $SERVANT_DIR
6+
7+git clone . $SERVANT_DIR
8+
9+cd $SERVANT_DIR
10+
11+# Make sure to pull the latest
12+
13+git remote add haskell-servant git@github.com:haskell-servant/servant-docs.git
14+
15+git fetch haskell-servant
16+
17+git reset --hard haskell-servant/gh-pages
18+
19+# Clear everything away
20+
21+git rm -rf $SERVANT_DIR/*
22+
23+# Switch back and build the haddocks
24+
25+cd -
26+
27+cabal configure --builddir=$SERVANT_DIR
28+
29+cabal haddock --hoogle --hyperlink-source --html-location='https://hackage.haskell.org/package/$pkg-$version/docs' --builddir=$SERVANT_DIR
30+
31+commit_hash=$(git rev-parse HEAD)
32+
33+# Move the HTML docs to the root
34+
35+cd $SERVANT_DIR
36+
37+rm *
38+rm -rf build
39+mv doc/html/servant-docs/* .
40+rm -r doc/
41+
42+# Add everything
43+
44+git add .
45+
46+git commit -m "Built from $commit_hash"
47+
48+# Push to update the pages
49+
50+git push haskell-servant HEAD:gh-pages
51+
52+rm -rf $SERVANT_DIR
servant-docs/example/greet.hsnew file+117
@@ -0,0 +1,117 @@
1+{-# LANGUAGE DataKinds #-}
2+{-# LANGUAGE DeriveGeneric #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE MultiParamTypeClasses #-}
5+{-# LANGUAGE OverloadedStrings #-}
6+{-# LANGUAGE TypeOperators #-}
7+{-# OPTIONS_GHC -fno-warn-orphans #-}
8+import Control.Lens
9+import Data.Aeson
10+import Data.Proxy
11+import Data.String.Conversions
12+import Data.Text (Text)
13+import GHC.Generics
14+import Servant.API
15+import Servant.Docs
16+
17+-- * Example
18+
19+-- | A greet message data type
20+newtype Greet = Greet Text
21+ deriving (Generic, Show)
22+
23+-- | We can get JSON support automatically. This will be used to parse
24+-- and encode a Greeting as 'JSON'.
25+instance FromJSON Greet
26+instance ToJSON Greet
27+
28+-- | We can also implement 'MimeRender' for additional formats like 'PlainText'.
29+instance MimeRender PlainText Greet where
30+ mimeRender Proxy (Greet s) = "\"" <> cs s <> "\""
31+
32+-- We add some useful annotations to our captures,
33+-- query parameters and request body to make the docs
34+-- really helpful.
35+instance ToCapture (Capture "name" Text) where
36+ toCapture _ = DocCapture "name" "name of the person to greet"
37+
38+instance ToCapture (Capture "greetid" Text) where
39+ toCapture _ = DocCapture "greetid" "identifier of the greet msg to remove"
40+
41+instance ToParam (QueryParam "capital" Bool) where
42+ toParam _ =
43+ DocQueryParam "capital"
44+ ["true", "false"]
45+ "Get the greeting message in uppercase (true) or not (false).\
46+ \Default is false."
47+ Normal
48+
49+instance ToParam (MatrixParam "lang" String) where
50+ toParam _ =
51+ DocQueryParam "lang"
52+ ["en", "sv", "fr"]
53+ "Get the greeting message selected language. Default is en."
54+ Normal
55+
56+instance ToSample Greet where
57+ toSample = Just $ Greet "Hello, haskeller!"
58+
59+ toSamples =
60+ [ ("If you use ?capital=true", Greet "HELLO, HASKELLER")
61+ , ("If you use ?capital=false", Greet "Hello, haskeller")
62+ ]
63+
64+-- We define some introductory sections, these will appear at the top of the
65+-- documentation.
66+--
67+-- We pass them in with 'docsWith', below. If you only want to add
68+-- introductions, you may use 'docsWithIntros'
69+intro1 :: DocIntro
70+intro1 = DocIntro "On proper introductions." -- The title
71+ [ "Hello there."
72+ , "As documentation is usually written for humans, it's often useful \
73+ \to introduce concepts with a few words." ] -- Elements are paragraphs
74+
75+intro2 :: DocIntro
76+intro2 = DocIntro "This title is below the last"
77+ [ "You'll also note that multiple intros are possible." ]
78+
79+
80+-- API specification
81+type TestApi =
82+ -- GET /hello/:name?capital={true, false} returns a Greet as JSON or PlainText
83+ "hello" :> MatrixParam "lang" String :> Capture "name" Text :> QueryParam "capital" Bool :> Get '[JSON, PlainText] Greet
84+
85+ -- POST /greet with a Greet as JSON in the request body,
86+ -- returns a Greet as JSON
87+ :<|> "greet" :> ReqBody '[JSON] Greet :> Post '[JSON] Greet
88+
89+ -- DELETE /greet/:greetid
90+ :<|> "greet" :> Capture "greetid" Text :> Delete
91+
92+testApi :: Proxy TestApi
93+testApi = Proxy
94+
95+-- Build some extra information for the DELETE /greet/:greetid endpoint. We
96+-- want to add documentation about a secret unicorn header and some extra
97+-- notes.
98+extra :: ExtraInfo TestApi
99+extra =
100+ extraInfo (Proxy :: Proxy ("greet" :> Capture "greetid" Text :> Delete)) $
101+ defAction & headers <>~ ["unicorns"]
102+ & notes <>~ [ DocNote "Title" ["This is some text"]
103+ , DocNote "Second secton" ["And some more"]
104+ ]
105+
106+-- Generate the data that lets us have API docs. This
107+-- is derived from the type as well as from
108+-- the 'ToCapture', 'ToParam' and 'ToSample' instances from above.
109+--
110+-- If you didn't want intros and extra information, you could just call:
111+--
112+-- > docs testAPI :: API
113+docsGreet :: API
114+docsGreet = docsWith [intro1, intro2] extra testApi
115+
116+main :: IO ()
117+main = putStrLn $ markdown docsGreet
servant-docs/example/greet.mdnew file+124
@@ -0,0 +1,124 @@
1+#### On proper introductions.
2+
3+Hello there.
4+
5+As documentation is usually written for humans, it's often useful to introduce concepts with a few words.
6+
7+#### This title is below the last
8+
9+You'll also note that multiple intros are possible.
10+
11+## POST /greet
12+
13+#### Request:
14+
15+- Supported content types are:
16+
17+ - `application/json`
18+
19+- Example: `application/json`
20+
21+```javascript
22+"Hello, haskeller!"
23+```
24+
25+#### Response:
26+
27+- Status code 201
28+
29+- Supported content types are:
30+
31+ - `application/json`
32+
33+- If you use ?capital=true
34+
35+```javascript
36+"HELLO, HASKELLER"
37+```
38+
39+- If you use ?capital=false
40+
41+```javascript
42+"Hello, haskeller"
43+```
44+
45+## GET /hello;lang=<value>/:name
46+
47+#### Captures:
48+
49+- *name*: name of the person to greet
50+
51+#### Matrix Parameters:
52+
53+**hello**:
54+
55+- lang
56+ - **Values**: *en, sv, fr*
57+ - **Description**: Get the greeting message selected language. Default is en.
58+
59+
60+
61+#### GET Parameters:
62+
63+- capital
64+ - **Values**: *true, false*
65+ - **Description**: Get the greeting message in uppercase (true) or not (false).Default is false.
66+
67+
68+#### Response:
69+
70+- Status code 200
71+
72+- Supported content types are:
73+
74+ - `application/json`
75+ - `text/plain;charset=utf-8`
76+
77+- If you use ?capital=true
78+
79+```javascript
80+"HELLO, HASKELLER"
81+```
82+
83+- If you use ?capital=true
84+
85+```
86+"HELLO, HASKELLER"
87+```
88+
89+- If you use ?capital=false
90+
91+```javascript
92+"Hello, haskeller"
93+```
94+
95+- If you use ?capital=false
96+
97+```
98+"Hello, haskeller"
99+```
100+
101+## DELETE /greet/:greetid
102+
103+#### Title
104+
105+This is some text
106+
107+#### Second secton
108+
109+And some more
110+
111+#### Captures:
112+
113+- *greetid*: identifier of the greet msg to remove
114+
115+
116+- This endpoint is sensitive to the value of the **unicorns** HTTP header.
117+
118+#### Response:
119+
120+- Status code 200
121+
122+- No response body
123+
124+
servant-docs/servant-docs.cabalnew file+71
@@ -0,0 +1,71 @@
1+name: servant-docs
2+version: 0.3
3+synopsis: generate API docs for your servant webservice
4+description:
5+ Library for generating API docs from a servant API definition.
6+ .
7+ Runnable example <https://github.com/haskell-servant/servant-docs/blob/master/example/greet.hs here>.
8+license: BSD3
9+license-file: LICENSE
10+author: Alp Mestanogullari, Sönke Hahn, Julian K. Arni
11+maintainer: alpmestan@gmail.com
12+copyright: 2014-2015 Zalora South East Asia Pte Ltd
13+category: Web
14+build-type: Simple
15+cabal-version: >=1.10
16+tested-with: GHC >= 7.8
17+homepage: http://haskell-servant.github.io/
18+Bug-reports: http://github.com/haskell-servant/servant-docs/issues
19+extra-source-files:
20+ CHANGELOG.md
21+ README.md
22+source-repository head
23+ type: git
24+ location: http://github.com/haskell-servant/servant-docs.git
25+
26+library
27+ exposed-modules:
28+ Servant.Docs
29+ , Servant.Docs.Internal
30+ build-depends:
31+ base >=4.7 && <5
32+ , bytestring
33+ , hashable
34+ , http-media >= 0.6
35+ , lens
36+ , servant >= 0.2.1
37+ , string-conversions
38+ , text
39+ , unordered-containers
40+ hs-source-dirs: src
41+ default-language: Haskell2010
42+ ghc-options: -Wall
43+
44+executable greet-docs
45+ main-is: greet.hs
46+ hs-source-dirs: example
47+ ghc-options: -Wall
48+ build-depends:
49+ base
50+ , aeson
51+ , lens
52+ , servant
53+ , servant-docs
54+ , string-conversions
55+ , text
56+ default-language: Haskell2010
57+
58+test-suite spec
59+ type: exitcode-stdio-1.0
60+ main-is: Spec.hs
61+ hs-source-dirs: test
62+ ghc-options: -Wall
63+ build-depends:
64+ base
65+ , aeson
66+ , hspec
67+ , servant
68+ , servant-docs
69+ , string-conversions
70+ default-language: Haskell2010
71+
servant-docs/shell.nixnew file+9
@@ -0,0 +1,9 @@
1+with (import <nixpkgs> {}).pkgs;
2+let modifiedHaskellPackages = haskellngPackages.override {
3+ overrides = self: super: {
4+ servant = self.callPackage ../servant {};
5+ servant-server = self.callPackage ./servant-server {};
6+ servant-docs = self.callPackage ./. {};
7+ };
8+ };
9+in modifiedHaskellPackages.servant-docs.env
servant-docs/src/Servant/Docs.hsnew file+168
@@ -0,0 +1,168 @@
1+-------------------------------------------------------------------------------
2+-- | This module lets you get API docs for free. It lets you generate
3+-- an 'API' from the type that represents your API using 'docs':
4+--
5+-- @docs :: 'HasDocs' api => 'Proxy' api -> 'API'@
6+--
7+-- Alternatively, if you wish to add one or more introductions to your
8+-- documentation, use 'docsWithIntros':
9+--
10+-- @'docsWithIntros' :: 'HasDocs' api => [DocIntro] -> 'Proxy' api -> 'API'@
11+--
12+-- You can then call 'markdown' on the 'API' value:
13+--
14+-- @'markdown' :: 'API' -> String@
15+--
16+-- or define a custom pretty printer:
17+--
18+-- @yourPrettyDocs :: 'API' -> String -- or blaze-html's HTML, or ...@
19+--
20+-- The only thing you'll need to do will be to implement some classes
21+-- for your captures, get parameters and request or response bodies.
22+--
23+-- Here is a complete example that you can run to see the markdown pretty
24+-- printer in action:
25+--
26+-- > {-# LANGUAGE DataKinds #-}
27+-- > {-# LANGUAGE DeriveGeneric #-}
28+-- > {-# LANGUAGE FlexibleInstances #-}
29+-- > {-# LANGUAGE MultiParamTypeClasses #-}
30+-- > {-# LANGUAGE OverloadedStrings #-}
31+-- > {-# LANGUAGE TypeOperators #-}
32+-- > {-# OPTIONS_GHC -fno-warn-orphans #-}
33+-- > import Data.Aeson
34+-- > import Data.Proxy
35+-- > import Data.String.Conversions
36+-- > import Data.Text (Text)
37+-- > import GHC.Generics
38+-- > import Servant.API
39+-- > import Servant.Docs
40+-- >
41+-- > -- * Example
42+-- >
43+-- > -- | A greet message data type
44+-- > newtype Greet = Greet Text
45+-- > deriving (Generic, Show)
46+-- >
47+-- > -- | We can get JSON support automatically. This will be used to parse
48+-- > -- and encode a Greeting as 'JSON'.
49+-- > instance FromJSON Greet
50+-- > instance ToJSON Greet
51+-- >
52+-- > -- | We can also implement 'MimeRender' for additional formats like 'PlainText'.
53+-- > instance MimeRender PlainText Greet where
54+-- > toByteString Proxy (Greet s) = "\"" <> cs s <> "\""
55+-- >
56+-- > -- We add some useful annotations to our captures,
57+-- > -- query parameters and request body to make the docs
58+-- > -- really helpful.
59+-- > instance ToCapture (Capture "name" Text) where
60+-- > toCapture _ = DocCapture "name" "name of the person to greet"
61+-- >
62+-- > instance ToCapture (Capture "greetid" Text) where
63+-- > toCapture _ = DocCapture "greetid" "identifier of the greet msg to remove"
64+-- >
65+-- > instance ToParam (QueryParam "capital" Bool) where
66+-- > toParam _ =
67+-- > DocQueryParam "capital"
68+-- > ["true", "false"]
69+-- > "Get the greeting message in uppercase (true) or not (false).\
70+-- > \Default is false."
71+-- > Normal
72+-- >
73+-- > instance ToParam (MatrixParam "lang" String) where
74+-- > toParam _ =
75+-- > DocQueryParam "lang"
76+-- > ["en", "sv", "fr"]
77+-- > "Get the greeting message selected language. Default is en."
78+-- > Normal
79+-- >
80+-- > instance ToSample Greet where
81+-- > toSample = Just $ Greet "Hello, haskeller!"
82+-- >
83+-- > toSamples =
84+-- > [ ("If you use ?capital=true", Greet "HELLO, HASKELLER")
85+-- > , ("If you use ?capital=false", Greet "Hello, haskeller")
86+-- > ]
87+-- >
88+-- > -- We define some introductory sections, these will appear at the top of the
89+-- > -- documentation.
90+-- > --
91+-- > -- We pass them in with 'docsWith', below. If you only want to add
92+-- > -- introductions, you may use 'docsWithIntros'
93+-- > intro1 :: DocIntro
94+-- > intro1 = DocIntro "On proper introductions." -- The title
95+-- > [ "Hello there."
96+-- > , "As documentation is usually written for humans, it's often useful \
97+-- > \to introduce concepts with a few words." ] -- Elements are paragraphs
98+-- >
99+-- > intro2 :: DocIntro
100+-- > intro2 = DocIntro "This title is below the last"
101+-- > [ "You'll also note that multiple intros are possible." ]
102+-- >
103+-- >
104+-- > -- API specification
105+-- > type TestApi =
106+-- > -- GET /hello/:name?capital={true, false} returns a Greet as JSON or PlainText
107+-- > "hello" :> MatrixParam "lang" String :> Capture "name" Text :> QueryParam "capital" Bool :> Get '[JSON, PlainText] Greet
108+-- >
109+-- > -- POST /greet with a Greet as JSON in the request body,
110+-- > -- returns a Greet as JSON
111+-- > :<|> "greet" :> ReqBody '[JSON] Greet :> Post '[JSON] Greet
112+-- >
113+-- > -- DELETE /greet/:greetid
114+-- > :<|> "greet" :> Capture "greetid" Text :> Delete
115+-- >
116+-- > testApi :: Proxy TestApi
117+-- > testApi = Proxy
118+-- >
119+-- > -- Build some extra information for the DELETE /greet/:greetid endpoint. We
120+-- > -- want to add documentation about a secret unicorn header and some extra
121+-- > -- notes.
122+-- > extra :: ExtraInfo TestApi
123+-- > extra =
124+-- > extraInfo (Proxy :: Proxy ("greet" :> Capture "greetid" Text :> Delete)) $
125+-- > defAction & headers <>~ ["unicorns"]
126+-- > & notes <>~ [ DocNote "Title" ["This is some text"]
127+-- > , DocNote "Second secton" ["And some more"]
128+-- > ]
129+-- >
130+-- > -- Generate the data that lets us have API docs. This
131+-- > -- is derived from the type as well as from
132+-- > -- the 'ToCapture', 'ToParam' and 'ToSample' instances from above.
133+-- > --
134+-- > -- If you didn't want intros and extra information, you could just call:
135+-- > --
136+-- > -- > docs testAPI :: API
137+-- > docsGreet :: API
138+-- > docsGreet = docsWith [intro1, intro2] extra testApi
139+-- >
140+-- > main :: IO ()
141+-- > main = putStrLn $ markdown docsGreet
142+module Servant.Docs
143+ ( -- * 'HasDocs' class and key functions
144+ HasDocs(..), docs, markdown
145+ -- * Generating docs with extra information
146+ , ExtraInfo(..), docsWith, docsWithIntros, extraInfo
147+
148+ , -- * Classes you need to implement for your types
149+ ToSample(..)
150+ , sampleByteString
151+ , sampleByteStrings
152+ , ToParam(..)
153+ , ToCapture(..)
154+
155+ , -- * ADTs to represent an 'API'
156+ Method(..)
157+ , Endpoint, path, method, defEndpoint
158+ , API, emptyAPI
159+ , DocCapture(..), capSymbol, capDesc
160+ , DocQueryParam(..), ParamKind(..), paramName, paramValues, paramDesc, paramKind
161+ , DocNote(..), noteTitle, noteBody
162+ , DocIntro(..)
163+ , Response(..), respStatus, respTypes, respBody, defResponse
164+ , Action, captures, headers, notes, params, rqtypes, rqbody, response, defAction
165+ , single
166+ ) where
167+
168+import Servant.Docs.Internal
servant-docs/src/Servant/Docs/Internal.hsnew file+803
@@ -0,0 +1,803 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE DataKinds #-}
3+{-# LANGUAGE DeriveGeneric #-}
4+{-# LANGUAGE FlexibleContexts #-}
5+{-# LANGUAGE FlexibleInstances #-}
6+{-# LANGUAGE OverloadedStrings #-}
7+{-# LANGUAGE PolyKinds #-}
8+{-# LANGUAGE ScopedTypeVariables #-}
9+{-# LANGUAGE TemplateHaskell #-}
10+{-# LANGUAGE TupleSections #-}
11+{-# LANGUAGE TypeFamilies #-}
12+{-# LANGUAGE TypeOperators #-}
13+{-# LANGUAGE UndecidableInstances #-}
14+module Servant.Docs.Internal where
15+
16+import Control.Applicative
17+import Control.Lens
18+import Data.ByteString.Lazy.Char8 (ByteString)
19+import Data.Hashable
20+import Data.HashMap.Strict (HashMap)
21+import Data.List
22+import Data.Maybe
23+import Data.Monoid
24+import Data.Ord (comparing)
25+import Data.Proxy
26+import Data.String.Conversions
27+import Data.Text (Text, pack, unpack)
28+import GHC.Exts (Constraint)
29+import GHC.Generics
30+import GHC.TypeLits
31+import Servant.API
32+import Servant.API.ContentTypes
33+import Servant.Utils.Links
34+
35+import qualified Data.HashMap.Strict as HM
36+import qualified Data.Text as T
37+import qualified Network.HTTP.Media as M
38+
39+-- | Supported HTTP request methods
40+data Method = DocDELETE -- ^ the DELETE method
41+ | DocGET -- ^ the GET method
42+ | DocPOST -- ^ the POST method
43+ | DocPUT -- ^ the PUT method
44+ deriving (Eq, Ord, Generic)
45+
46+instance Show Method where
47+ show DocGET = "GET"
48+ show DocPOST = "POST"
49+ show DocDELETE = "DELETE"
50+ show DocPUT = "PUT"
51+
52+instance Hashable Method
53+
54+-- | An 'Endpoint' type that holds the 'path' and the 'method'.
55+--
56+-- Gets used as the key in the 'API' hashmap. Modify 'defEndpoint'
57+-- or any 'Endpoint' value you want using the 'path' and 'method'
58+-- lenses to tweak.
59+--
60+-- @
61+-- λ> 'defEndpoint'
62+-- GET /
63+-- λ> 'defEndpoint' & 'path' '<>~' ["foo"]
64+-- GET /foo
65+-- λ> 'defEndpoint' & 'path' '<>~' ["foo"] & 'method' '.~' 'DocPOST'
66+-- POST /foo
67+-- @
68+data Endpoint = Endpoint
69+ { _path :: [String] -- type collected
70+ , _method :: Method -- type collected
71+ } deriving (Eq, Ord, Generic)
72+
73+instance Show Endpoint where
74+ show (Endpoint p m) =
75+ show m ++ " " ++ showPath p
76+
77+-- |
78+-- Render a path as a '/'-delimited string
79+--
80+showPath :: [String] -> String
81+showPath [] = "/"
82+showPath ps = concatMap ('/' :) ps
83+
84+-- | An 'Endpoint' whose path is `"/"` and whose method is 'DocGET'
85+--
86+-- Here's how you can modify it:
87+--
88+-- @
89+-- λ> 'defEndpoint'
90+-- GET /
91+-- λ> 'defEndpoint' & 'path' '<>~' ["foo"]
92+-- GET /foo
93+-- λ> 'defEndpoint' & 'path' '<>~' ["foo"] & 'method' '.~' 'DocPOST'
94+-- POST /foo
95+-- @
96+defEndpoint :: Endpoint
97+defEndpoint = Endpoint [] DocGET
98+
99+instance Hashable Endpoint
100+
101+-- | Our API documentation type, a product of top-level information and a good
102+-- old hashmap from 'Endpoint' to 'Action'
103+data API = API
104+ { _apiIntros :: [DocIntro]
105+ , _apiEndpoints :: HashMap Endpoint Action
106+ } deriving (Eq, Show)
107+
108+instance Monoid API where
109+ API a1 b1 `mappend` API a2 b2 = API (a1 <> a2) (b1 <> b2)
110+ mempty = API mempty mempty
111+
112+-- | An empty 'API'
113+emptyAPI :: API
114+emptyAPI = mempty
115+
116+-- | A type to represent captures. Holds the name of the capture
117+-- and a description.
118+--
119+-- Write a 'ToCapture' instance for your captured types.
120+data DocCapture = DocCapture
121+ { _capSymbol :: String -- type supplied
122+ , _capDesc :: String -- user supplied
123+ } deriving (Eq, Ord, Show)
124+
125+-- | A type to represent a /GET/ parameter from the Query String. Holds its name,
126+-- the possible values (leave empty if there isn't a finite number of them),
127+-- and a description of how it influences the output or behavior.
128+--
129+-- Write a 'ToParam' instance for your GET parameter types
130+data DocQueryParam = DocQueryParam
131+ { _paramName :: String -- type supplied
132+ , _paramValues :: [String] -- user supplied
133+ , _paramDesc :: String -- user supplied
134+ , _paramKind :: ParamKind
135+ } deriving (Eq, Ord, Show)
136+
137+-- | An introductory paragraph for your documentation. You can pass these to
138+-- 'docsWithIntros'.
139+data DocIntro = DocIntro
140+ { _introTitle :: String -- ^ Appears above the intro blob
141+ , _introBody :: [String] -- ^ Each String is a paragraph.
142+ } deriving (Eq, Show)
143+
144+instance Ord DocIntro where
145+ compare = comparing _introTitle
146+
147+-- | A type to represent extra notes that may be attached to an 'Action'.
148+--
149+-- This is intended to be used when writing your own HasDocs instances to
150+-- add extra sections to your endpoint's documentation.
151+data DocNote = DocNote
152+ { _noteTitle :: String
153+ , _noteBody :: [String]
154+ } deriving (Eq, Ord, Show)
155+
156+-- | Type of extra information that a user may wish to "union" with their
157+-- documentation.
158+--
159+-- These are intended to be built using extraInfo.
160+-- Multiple ExtraInfo may be combined with the monoid instance.
161+newtype ExtraInfo layout = ExtraInfo (HashMap Endpoint Action)
162+instance Monoid (ExtraInfo a) where
163+ mempty = ExtraInfo mempty
164+ ExtraInfo a `mappend` ExtraInfo b =
165+ ExtraInfo $ HM.unionWith combineAction a b
166+
167+-- | Type of GET parameter:
168+--
169+-- - Normal corresponds to @QueryParam@, i.e your usual GET parameter
170+-- - List corresponds to @QueryParams@, i.e GET parameters with multiple values
171+-- - Flag corresponds to @QueryFlag@, i.e a value-less GET parameter
172+data ParamKind = Normal | List | Flag
173+ deriving (Eq, Ord, Show)
174+
175+-- | A type to represent an HTTP response. Has an 'Int' status, a list of
176+-- possible 'MediaType's, and a list of example 'ByteString' response bodies.
177+-- Tweak 'defResponse' using the 'respStatus', 'respTypes' and 'respBody'
178+-- lenses if you want.
179+--
180+-- If you want to respond with a non-empty response body, you'll most likely
181+-- want to write a 'ToSample' instance for the type that'll be represented
182+-- as encoded data in the response.
183+--
184+-- Can be tweaked with three lenses.
185+--
186+-- > λ> defResponse
187+-- > Response {_respStatus = 200, _respTypes = [], _respBody = []}
188+-- > λ> defResponse & respStatus .~ 204 & respBody .~ [("If everything goes well", "{ \"status\": \"ok\" }")]
189+-- > Response {_respStatus = 204, _respTypes = [], _respBody = [("If everything goes well", "{ \"status\": \"ok\" }")]}
190+data Response = Response
191+ { _respStatus :: Int
192+ , _respTypes :: [M.MediaType]
193+ , _respBody :: [(Text, M.MediaType, ByteString)]
194+ } deriving (Eq, Ord, Show)
195+
196+-- | Default response: status code 200, no response body.
197+--
198+-- Can be tweaked with two lenses.
199+--
200+-- > λ> defResponse
201+-- > Response {_respStatus = 200, _respBody = Nothing}
202+-- > λ> defResponse & respStatus .~ 204 & respBody .~ Just "[]"
203+-- > Response {_respStatus = 204, _respBody = Just "[]"}
204+defResponse :: Response
205+defResponse = Response 200 [] []
206+
207+-- | A datatype that represents everything that can happen
208+-- at an endpoint, with its lenses:
209+--
210+-- - List of captures ('captures')
211+-- - List of GET parameters ('params')
212+-- - What the request body should look like, if any is requested ('rqbody')
213+-- - What the response should be if everything goes well ('response')
214+--
215+-- You can tweak an 'Action' (like the default 'defAction') with these lenses
216+-- to transform an action and add some information to it.
217+data Action = Action
218+ { _captures :: [DocCapture] -- type collected + user supplied info
219+ , _headers :: [Text] -- type collected
220+ , _params :: [DocQueryParam] -- type collected + user supplied info
221+ , _notes :: [DocNote] -- user supplied
222+ , _mxParams :: [(String, [DocQueryParam])] -- type collected + user supplied info
223+ , _rqtypes :: [M.MediaType] -- type collected
224+ , _rqbody :: [(M.MediaType, ByteString)] -- user supplied
225+ , _response :: Response -- user supplied
226+ } deriving (Eq, Ord, Show)
227+
228+-- | Combine two Actions, we can't make a monoid as merging Response breaks the
229+-- laws.
230+--
231+-- As such, we invent a non-commutative, left associative operation
232+-- 'combineAction' to mush two together taking the response, body and content
233+-- types from the very left.
234+combineAction :: Action -> Action -> Action
235+Action c h p n m ts body resp `combineAction` Action c' h' p' n' m' _ _ _ =
236+ Action (c <> c') (h <> h') (p <> p') (n <> n') (m <> m') ts body resp
237+
238+-- Default 'Action'. Has no 'captures', no GET 'params', expects
239+-- no request body ('rqbody') and the typical response is 'defResponse'.
240+--
241+-- Tweakable with lenses.
242+--
243+-- > λ> defAction
244+-- > Action {_captures = [], _headers = [], _params = [], _mxParams = [], _rqbody = Nothing, _response = Response {_respStatus = 200, _respBody = Nothing}}
245+-- > λ> defAction & response.respStatus .~ 201
246+-- > Action {_captures = [], _headers = [], _params = [], _mxParams = [], _rqbody = Nothing, _response = Response {_respStatus = 201, _respBody = Nothing}}
247+defAction :: Action
248+defAction =
249+ Action []
250+ []
251+ []
252+ []
253+ []
254+ []
255+ []
256+ defResponse
257+
258+-- | Create an API that's comprised of a single endpoint.
259+-- 'API' is a 'Monoid', so combine multiple endpoints with
260+-- 'mappend' or '<>'.
261+single :: Endpoint -> Action -> API
262+single e a = API mempty (HM.singleton e a)
263+
264+-- gimme some lenses
265+makeLenses ''API
266+makeLenses ''Endpoint
267+makeLenses ''DocCapture
268+makeLenses ''DocQueryParam
269+makeLenses ''DocIntro
270+makeLenses ''DocNote
271+makeLenses ''Response
272+makeLenses ''Action
273+
274+-- | Generate the docs for a given API that implements 'HasDocs'. This is the
275+-- default way to create documentation.
276+docs :: HasDocs (Canonicalize layout) => Proxy layout -> API
277+docs p = docsFor (canonicalize p) (defEndpoint, defAction)
278+
279+-- | Closed type family, check if endpoint is exactly within API.
280+
281+-- We aren't sure what affects how an Endpoint is built up, so we require an
282+-- exact match.
283+type family IsIn (endpoint :: *) (api :: *) :: Constraint where
284+ IsIn e (sa :<|> sb) = Or (IsIn e sa) (IsIn e sb)
285+ IsIn (e :> sa) (e :> sb) = IsIn sa sb
286+ IsIn e e = ()
287+
288+-- | Create an 'ExtraInfo' that is garunteed to be within the given API layout.
289+--
290+-- The safety here is to ensure that you only add custom documentation to an
291+-- endpoint that actually exists within your API.
292+--
293+-- > extra :: ExtraInfo TestApi
294+-- > extra =
295+-- > extraInfo (Proxy :: Proxy ("greet" :> Capture "greetid" Text :> Delete)) $
296+-- > defAction & headers <>~ ["unicorns"]
297+-- > & notes <>~ [ DocNote "Title" ["This is some text"]
298+-- > , DocNote "Second secton" ["And some more"]
299+-- > ]
300+
301+extraInfo :: (IsIn endpoint layout, HasLink endpoint, HasDocs endpoint)
302+ => Proxy endpoint -> Action -> ExtraInfo layout
303+extraInfo p action =
304+ let api = docsFor p (defEndpoint, defAction)
305+ -- Assume one endpoint, HasLink constraint means that we should only ever
306+ -- point at one endpoint.
307+ in ExtraInfo $ api ^. apiEndpoints & traversed .~ action
308+
309+-- | Generate documentation given some extra introductions (in the form of
310+-- 'DocInfo') and some extra endpoint documentation (in the form of
311+-- 'ExtraInfo'.
312+--
313+-- The extra introductions will be prepended to the top of the documentation,
314+-- before the specific endpoint documentation. The extra endpoint documentation
315+-- will be "unioned" with the automatically generated endpoint documentation.
316+--
317+-- You are expected to build up the ExtraInfo with the Monoid instance and
318+-- 'extraInfo'.
319+--
320+-- If you only want to add an introduction, use 'docsWithIntros'.
321+docsWith :: HasDocs (Canonicalize layout)
322+ => [DocIntro]
323+ -> ExtraInfo layout
324+ -> Proxy layout
325+ -> API
326+docsWith intros (ExtraInfo endpoints) p =
327+ docs p & apiIntros <>~ intros
328+ & apiEndpoints %~ HM.unionWith combineAction endpoints
329+
330+
331+-- | Generate the docs for a given API that implements 'HasDocs' with with any
332+-- number of introduction(s)
333+docsWithIntros :: HasDocs (Canonicalize layout) => [DocIntro] -> Proxy layout -> API
334+docsWithIntros intros = docsWith intros mempty
335+
336+-- | The class that abstracts away the impact of API combinators
337+-- on documentation generation.
338+class HasDocs layout where
339+ docsFor :: Proxy layout -> (Endpoint, Action) -> API
340+
341+-- | The class that lets us display a sample input or output in the supported
342+-- content-types when generating documentation for endpoints that either:
343+--
344+-- - expect a request body, or
345+-- - return a non empty response body
346+--
347+-- Example of an instance:
348+--
349+-- > {-# LANGUAGE DeriveGeneric #-}
350+-- > {-# LANGUAGE OverloadedStrings #-}
351+-- >
352+-- > import Data.Aeson
353+-- > import Data.Text
354+-- > import GHC.Generics
355+-- >
356+-- > data Greet = Greet { _msg :: Text }
357+-- > deriving (Generic, Show)
358+-- >
359+-- > instance FromJSON Greet
360+-- > instance ToJSON Greet
361+-- >
362+-- > instance ToSample Greet where
363+-- > toSample = Just g
364+-- >
365+-- > where g = Greet "Hello, haskeller!"
366+--
367+-- You can also instantiate this class using 'toSamples' instead of
368+-- 'toSample': it lets you specify different responses along with
369+-- some context (as 'Text') that explains when you're supposed to
370+-- get the corresponding response.
371+class ToSample a where
372+ {-# MINIMAL (toSample | toSamples) #-}
373+ toSample :: Maybe a
374+ toSample = snd <$> listToMaybe samples
375+ where samples = toSamples :: [(Text, a)]
376+
377+ toSamples :: [(Text, a)]
378+ toSamples = maybe [] (return . ("",)) s
379+ where s = toSample :: Maybe a
380+
381+-- | Synthesise a sample value of a type, encoded in the specified media types.
382+sampleByteString
383+ :: forall ctypes a. (ToSample a, IsNonEmpty ctypes, AllMimeRender ctypes a)
384+ => Proxy ctypes
385+ -> Proxy a
386+ -> [(M.MediaType, ByteString)]
387+sampleByteString ctypes@Proxy Proxy =
388+ maybe [] (allMimeRender ctypes) (toSample :: Maybe a)
389+
390+-- | Synthesise a list of sample values of a particular type, encoded in the
391+-- specified media types.
392+sampleByteStrings
393+ :: forall ctypes a. (ToSample a, IsNonEmpty ctypes, AllMimeRender ctypes a)
394+ => Proxy ctypes
395+ -> Proxy a
396+ -> [(Text, M.MediaType, ByteString)]
397+sampleByteStrings ctypes@Proxy Proxy =
398+ let samples = toSamples :: [(Text, a)]
399+ enc (t, s) = uncurry (t,,) <$> allMimeRender ctypes s
400+ in concatMap enc samples
401+
402+-- | Generate a list of 'MediaType' values describing the content types
403+-- accepted by an API component.
404+class SupportedTypes (list :: [*]) where
405+ supportedTypes :: Proxy list -> [M.MediaType]
406+
407+instance SupportedTypes '[] where
408+ supportedTypes Proxy = []
409+
410+instance (Accept ctype, SupportedTypes rest) => SupportedTypes (ctype ': rest)
411+ where
412+ supportedTypes Proxy =
413+ contentType (Proxy :: Proxy ctype) : supportedTypes (Proxy :: Proxy rest)
414+
415+-- | The class that helps us automatically get documentation
416+-- for GET parameters.
417+--
418+-- Example of an instance:
419+--
420+-- > instance ToParam (QueryParam "capital" Bool) where
421+-- > toParam _ =
422+-- > DocQueryParam "capital"
423+-- > ["true", "false"]
424+-- > "Get the greeting message in uppercase (true) or not (false). Default is false."
425+class ToParam t where
426+ toParam :: Proxy t -> DocQueryParam
427+
428+-- | The class that helps us automatically get documentation
429+-- for URL captures.
430+--
431+-- Example of an instance:
432+--
433+-- > instance ToCapture (Capture "name" Text) where
434+-- > toCapture _ = DocCapture "name" "name of the person to greet"
435+class ToCapture c where
436+ toCapture :: Proxy c -> DocCapture
437+
438+-- | Generate documentation in Markdown format for
439+-- the given 'API'.
440+markdown :: API -> String
441+markdown api = unlines $
442+ introsStr (api ^. apiIntros)
443+ ++ (concatMap (uncurry printEndpoint) . sort . HM.toList $ api ^. apiEndpoints)
444+
445+ where printEndpoint :: Endpoint -> Action -> [String]
446+ printEndpoint endpoint action =
447+ str :
448+ "" :
449+ notesStr (action ^. notes) ++
450+ capturesStr (action ^. captures) ++
451+ mxParamsStr (action ^. mxParams) ++
452+ headersStr (action ^. headers) ++
453+ paramsStr (action ^. params) ++
454+ rqbodyStr (action ^. rqtypes) (action ^. rqbody) ++
455+ responseStr (action ^. response) ++
456+ []
457+
458+ where str = "## " ++ show (endpoint^.method)
459+ ++ " " ++ showPath (endpoint^.path)
460+
461+ introsStr :: [DocIntro] -> [String]
462+ introsStr = concatMap introStr
463+
464+ introStr :: DocIntro -> [String]
465+ introStr i =
466+ ("#### " ++ i ^. introTitle) :
467+ "" :
468+ intersperse "" (i ^. introBody) ++
469+ "" :
470+ []
471+
472+ notesStr :: [DocNote] -> [String]
473+ notesStr = concatMap noteStr
474+
475+ noteStr :: DocNote -> [String]
476+ noteStr nt =
477+ ("#### " ++ nt ^. noteTitle) :
478+ "" :
479+ intersperse "" (nt ^. noteBody) ++
480+ "" :
481+ []
482+
483+ capturesStr :: [DocCapture] -> [String]
484+ capturesStr [] = []
485+ capturesStr l =
486+ "#### Captures:" :
487+ "" :
488+ map captureStr l ++
489+ "" :
490+ []
491+
492+ captureStr cap =
493+ "- *" ++ (cap ^. capSymbol) ++ "*: " ++ (cap ^. capDesc)
494+
495+ mxParamsStr :: [(String, [DocQueryParam])] -> [String]
496+ mxParamsStr [] = []
497+ mxParamsStr l =
498+ "#### Matrix Parameters:" :
499+ "" :
500+ map segmentStr l
501+ segmentStr :: (String, [DocQueryParam]) -> String
502+ segmentStr (segment, l) = unlines $
503+ ("**" ++ segment ++ "**:") :
504+ "" :
505+ map paramStr l ++
506+ "" :
507+ []
508+
509+ headersStr :: [Text] -> [String]
510+ headersStr [] = []
511+ headersStr l = [""] ++ map headerStr l ++ [""]
512+
513+ where headerStr hname = "- This endpoint is sensitive to the value of the **"
514+ ++ unpack hname ++ "** HTTP header."
515+
516+ paramsStr :: [DocQueryParam] -> [String]
517+ paramsStr [] = []
518+ paramsStr l =
519+ "#### GET Parameters:" :
520+ "" :
521+ map paramStr l ++
522+ "" :
523+ []
524+
525+ paramStr param = unlines $
526+ ("- " ++ param ^. paramName) :
527+ (if (not (null values) || param ^. paramKind /= Flag)
528+ then [" - **Values**: *" ++ intercalate ", " values ++ "*"]
529+ else []) ++
530+ (" - **Description**: " ++ param ^. paramDesc) :
531+ (if (param ^. paramKind == List)
532+ then [" - This parameter is a **list**. All GET parameters with the name "
533+ ++ param ^. paramName ++ "[] will forward their values in a list to the handler."]
534+ else []) ++
535+ (if (param ^. paramKind == Flag)
536+ then [" - This parameter is a **flag**. This means no value is expected to be associated to this parameter."]
537+ else []) ++
538+ []
539+
540+ where values = param ^. paramValues
541+
542+ rqbodyStr :: [M.MediaType] -> [(M.MediaType, ByteString)]-> [String]
543+ rqbodyStr [] [] = []
544+ rqbodyStr types samples =
545+ ["#### Request:", ""]
546+ <> formatTypes types
547+ <> concatMap formatBody samples
548+
549+ formatTypes [] = []
550+ formatTypes ts = ["- Supported content types are:", ""]
551+ <> map (\t -> " - `" <> show t <> "`") ts
552+ <> [""]
553+
554+ formatBody (m, b) =
555+ "- Example: `" <> cs (show m) <> "`" :
556+ contentStr m b
557+
558+ markdownForType mime_type =
559+ case (M.mainType mime_type, M.subType mime_type) of
560+ ("text", "html") -> "html"
561+ ("application", "xml") -> "xml"
562+ ("application", "json") -> "javascript"
563+ ("application", "javascript") -> "javascript"
564+ ("text", "css") -> "css"
565+ (_, _) -> ""
566+
567+ contentStr mime_type body =
568+ "" :
569+ "```" <> markdownForType mime_type :
570+ cs body :
571+ "```" :
572+ "" :
573+ []
574+
575+ responseStr :: Response -> [String]
576+ responseStr resp =
577+ "#### Response:" :
578+ "" :
579+ ("- Status code " ++ show (resp ^. respStatus)) :
580+ "" :
581+ formatTypes (resp ^. respTypes) ++
582+ bodies
583+
584+ where bodies = case resp ^. respBody of
585+ [] -> ["- No response body\n"]
586+ [("", t, r)] -> "- Response body as below." : contentStr t r
587+ xs ->
588+ concatMap (\(ctx, t, r) -> ("- " <> T.unpack ctx) : contentStr t r) xs
589+
590+-- * Instances
591+
592+-- | The generated docs for @a ':<|>' b@ just appends the docs
593+-- for @a@ with the docs for @b@.
594+instance (HasDocs layout1, HasDocs layout2)
595+ => HasDocs (layout1 :<|> layout2) where
596+
597+ docsFor Proxy (ep, action) = docsFor p1 (ep, action) <> docsFor p2 (ep, action)
598+
599+ where p1 :: Proxy layout1
600+ p1 = Proxy
601+
602+ p2 :: Proxy layout2
603+ p2 = Proxy
604+
605+-- | @"books" :> 'Capture' "isbn" Text@ will appear as
606+-- @/books/:isbn@ in the docs.
607+instance (KnownSymbol sym, ToCapture (Capture sym a), HasDocs sublayout)
608+ => HasDocs (Capture sym a :> sublayout) where
609+
610+ docsFor Proxy (endpoint, action) =
611+ docsFor sublayoutP (endpoint', action')
612+
613+ where sublayoutP = Proxy :: Proxy sublayout
614+ captureP = Proxy :: Proxy (Capture sym a)
615+
616+ action' = over captures (|> toCapture captureP) action
617+ endpoint' = over path (\p -> p ++ [":" ++ symbolVal symP]) endpoint
618+ symP = Proxy :: Proxy sym
619+
620+
621+instance HasDocs Delete where
622+ docsFor Proxy (endpoint, action) =
623+ single endpoint' action'
624+
625+ where endpoint' = endpoint & method .~ DocDELETE
626+
627+ action' = action & response.respBody .~ []
628+ & response.respStatus .~ 204
629+
630+instance (ToSample a, IsNonEmpty cts, AllMimeRender cts a, SupportedTypes cts)
631+ => HasDocs (Get cts a) where
632+ docsFor Proxy (endpoint, action) =
633+ single endpoint' action'
634+
635+ where endpoint' = endpoint & method .~ DocGET
636+ action' = action & response.respBody .~ sampleByteStrings t p
637+ & response.respTypes .~ supportedTypes t
638+ t = Proxy :: Proxy cts
639+ p = Proxy :: Proxy a
640+
641+instance (KnownSymbol sym, HasDocs sublayout)
642+ => HasDocs (Header sym a :> sublayout) where
643+ docsFor Proxy (endpoint, action) =
644+ docsFor sublayoutP (endpoint, action')
645+
646+ where sublayoutP = Proxy :: Proxy sublayout
647+ action' = over headers (|> headername) action
648+ headername = pack $ symbolVal (Proxy :: Proxy sym)
649+
650+instance (ToSample a, IsNonEmpty cts, AllMimeRender cts a, SupportedTypes cts)
651+ => HasDocs (Post cts a) where
652+ docsFor Proxy (endpoint, action) =
653+ single endpoint' action'
654+
655+ where endpoint' = endpoint & method .~ DocPOST
656+ action' = action & response.respBody .~ sampleByteStrings t p
657+ & response.respTypes .~ supportedTypes t
658+ & response.respStatus .~ 201
659+ t = Proxy :: Proxy cts
660+ p = Proxy :: Proxy a
661+
662+instance (ToSample a, IsNonEmpty cts, AllMimeRender cts a, SupportedTypes cts)
663+ => HasDocs (Put cts a) where
664+ docsFor Proxy (endpoint, action) =
665+ single endpoint' action'
666+
667+ where endpoint' = endpoint & method .~ DocPUT
668+ action' = action & response.respBody .~ sampleByteStrings t p
669+ & response.respTypes .~ supportedTypes t
670+ & response.respStatus .~ 200
671+ t = Proxy :: Proxy cts
672+ p = Proxy :: Proxy a
673+
674+instance (KnownSymbol sym, ToParam (QueryParam sym a), HasDocs sublayout)
675+ => HasDocs (QueryParam sym a :> sublayout) where
676+
677+ docsFor Proxy (endpoint, action) =
678+ docsFor sublayoutP (endpoint, action')
679+
680+ where sublayoutP = Proxy :: Proxy sublayout
681+ paramP = Proxy :: Proxy (QueryParam sym a)
682+ action' = over params (|> toParam paramP) action
683+
684+instance (KnownSymbol sym, ToParam (QueryParams sym a), HasDocs sublayout)
685+ => HasDocs (QueryParams sym a :> sublayout) where
686+
687+ docsFor Proxy (endpoint, action) =
688+ docsFor sublayoutP (endpoint, action')
689+
690+ where sublayoutP = Proxy :: Proxy sublayout
691+ paramP = Proxy :: Proxy (QueryParams sym a)
692+ action' = over params (|> toParam paramP) action
693+
694+
695+instance (KnownSymbol sym, ToParam (QueryFlag sym), HasDocs sublayout)
696+ => HasDocs (QueryFlag sym :> sublayout) where
697+
698+ docsFor Proxy (endpoint, action) =
699+ docsFor sublayoutP (endpoint, action')
700+
701+ where sublayoutP = Proxy :: Proxy sublayout
702+ paramP = Proxy :: Proxy (QueryFlag sym)
703+ action' = over params (|> toParam paramP) action
704+
705+
706+instance (KnownSymbol sym, ToParam (MatrixParam sym a), HasDocs sublayout)
707+ => HasDocs (MatrixParam sym a :> sublayout) where
708+
709+ docsFor Proxy (endpoint, action) =
710+ docsFor sublayoutP (endpoint', action')
711+
712+ where sublayoutP = Proxy :: Proxy sublayout
713+ paramP = Proxy :: Proxy (MatrixParam sym a)
714+ segment = endpoint ^. (path._last)
715+ segment' = action ^. (mxParams._last._1)
716+ endpoint' = over (path._last) (\p -> p ++ ";" ++ symbolVal symP ++ "=<value>") endpoint
717+
718+ action' = if segment' /= segment
719+ -- This is the first matrix parameter for this segment, insert a new entry into the mxParams list
720+ then over mxParams (|> (segment, [toParam paramP])) action
721+ -- We've already inserted a matrix parameter for this segment, append to the existing list
722+ else action & mxParams._last._2 <>~ [toParam paramP]
723+ symP = Proxy :: Proxy sym
724+
725+
726+instance (KnownSymbol sym, {- ToParam (MatrixParams sym a), -} HasDocs sublayout)
727+ => HasDocs (MatrixParams sym a :> sublayout) where
728+
729+ docsFor Proxy (endpoint, action) =
730+ docsFor sublayoutP (endpoint', action)
731+
732+ where sublayoutP = Proxy :: Proxy sublayout
733+ endpoint' = over path (\p -> p ++ [";" ++ symbolVal symP ++ "=<value>"]) endpoint
734+ symP = Proxy :: Proxy sym
735+
736+
737+instance (KnownSymbol sym, {- ToParam (MatrixFlag sym), -} HasDocs sublayout)
738+ => HasDocs (MatrixFlag sym :> sublayout) where
739+
740+ docsFor Proxy (endpoint, action) =
741+ docsFor sublayoutP (endpoint', action)
742+
743+ where sublayoutP = Proxy :: Proxy sublayout
744+
745+ endpoint' = over path (\p -> p ++ [";" ++ symbolVal symP]) endpoint
746+ symP = Proxy :: Proxy sym
747+
748+instance HasDocs Raw where
749+ docsFor _proxy (endpoint, action) =
750+ single endpoint action
751+
752+-- TODO: We use 'AllMimeRender' here because we need to be able to show the
753+-- example data. However, there's no reason to believe that the instances of
754+-- 'AllMimeUnrender' and 'AllMimeRender' actually agree (or to suppose that
755+-- both are even defined) for any particular type.
756+instance (ToSample a, IsNonEmpty cts, AllMimeRender cts a, HasDocs sublayout, SupportedTypes cts)
757+ => HasDocs (ReqBody cts a :> sublayout) where
758+
759+ docsFor Proxy (endpoint, action) =
760+ docsFor sublayoutP (endpoint, action')
761+
762+ where sublayoutP = Proxy :: Proxy sublayout
763+ action' = action & rqbody .~ sampleByteString t p
764+ & rqtypes .~ supportedTypes t
765+ t = Proxy :: Proxy cts
766+ p = Proxy :: Proxy a
767+
768+instance (KnownSymbol path, HasDocs sublayout) => HasDocs (path :> sublayout) where
769+
770+ docsFor Proxy (endpoint, action) =
771+ docsFor sublayoutP (endpoint', action)
772+
773+ where sublayoutP = Proxy :: Proxy sublayout
774+ endpoint' = endpoint & path <>~ [symbolVal pa]
775+ pa = Proxy :: Proxy path
776+
777+{-
778+
779+-- | Serve your API's docs as markdown embedded in an html \<pre> tag.
780+--
781+-- > type MyApi = "users" :> Get [User]
782+-- > :<|> "docs :> Raw
783+-- >
784+-- > apiProxy :: Proxy MyApi
785+-- > apiProxy = Proxy
786+-- >
787+-- > server :: Server MyApi
788+-- > server = listUsers
789+-- > :<|> serveDocumentation apiProxy
790+serveDocumentation :: HasDocs api => Proxy api -> Server Raw
791+serveDocumentation proxy _request respond =
792+ respond $ responseLBS ok200 [] $ cs $ toHtml $ markdown $ docs proxy
793+
794+toHtml :: String -> String
795+toHtml md =
796+ "<html>" ++
797+ "<body>" ++
798+ "<pre>" ++
799+ md ++
800+ "</pre>" ++
801+ "</body>" ++
802+ "</html>"
803+-}
servant-docs/test/Servant/DocsSpec.hsnew file+64
@@ -0,0 +1,64 @@
1+{-# LANGUAGE DataKinds #-}
2+{-# LANGUAGE DeriveGeneric #-}
3+{-# LANGUAGE FlexibleInstances #-}
4+{-# LANGUAGE MultiParamTypeClasses #-}
5+{-# LANGUAGE TypeOperators #-}
6+{-# LANGUAGE TypeSynonymInstances #-}
7+{-# OPTIONS_GHC -fno-warn-orphans #-}
8+module Servant.DocsSpec where
9+
10+import Data.Aeson
11+import Data.Proxy
12+import Data.String.Conversions (cs)
13+import GHC.Generics
14+import Test.Hspec
15+
16+import Servant.API
17+import Servant.Docs.Internal
18+
19+spec :: Spec
20+spec = describe "Servant.Docs" $ do
21+
22+ describe "markdown" $ do
23+ let md = markdown (docs (Proxy :: Proxy TestApi1))
24+
25+ it "mentions supported content-types" $ do
26+ md `shouldContain` "application/json"
27+ md `shouldContain` "text/plain;charset=utf-8"
28+
29+ it "mentions status codes" $ do
30+ md `shouldContain` "Status code 200"
31+ md `shouldContain` "Status code 201"
32+
33+ it "mentions methods" $ do
34+ md `shouldContain` "POST"
35+ md `shouldContain` "GET"
36+
37+ it "contains response samples" $ do
38+ md `shouldContain` "{\"dt1field1\":\"field 1\",\"dt1field2\":13}"
39+ it "contains request body samples" $ do
40+ md `shouldContain` "17"
41+-- * APIs
42+
43+data Datatype1 = Datatype1 { dt1field1 :: String
44+ , dt1field2 :: Int
45+ } deriving (Eq, Show, Generic)
46+
47+instance ToJSON Datatype1
48+
49+instance ToSample Datatype1 where
50+ toSample = Just $ Datatype1 "field 1" 13
51+
52+instance ToSample String where
53+ toSample = Just "a string"
54+
55+instance ToSample Int where
56+ toSample = Just 17
57+
58+instance MimeRender PlainText Int where
59+ mimeRender _ = cs . show
60+
61+
62+type TestApi1 = Get '[JSON, PlainText] Int
63+ :<|> ReqBody '[JSON] String :> Post '[JSON] Datatype1
64+
servant-docs/test/Spec.hsnew file+1
@@ -0,0 +1 @@
1+{-# OPTIONS_GHC -F -pgmF hspec-discover #-}