on master help sign in
Merged in 0.3
commit330e9abcaac73549dd354299d4e50bdd414d361b authorDaniel Larsson <daniel.j.larsson@gmail.com> dateTue 6 Jan 2015, 14:29 (12 years ago) parent6f1066244efc7f
6 files changed+102−46
CHANGELOG.md+6 README.md+1−1 example/greet.hs+5 example/greet.md+27−12 servant-docs.cabal+5−2 src/Servant/Docs.hs+58−31
CHANGELOG.mdnew file+6
@@ -0,0 +1,6 @@
1+0.3
2+---
3+
4+* Add the ability to display multiple responses, with some accompanying `Text` to describe the context in which we get the corresponding JSON.
5+* Expose the `headers` lens
6+* Represent an endpoint's path as `[String]` (previously `String`), fixing a corner case where the leading `/` would be missing.
README.md+1−1
@@ -4,7 +4,7 @@
44
55![servant](https://raw.githubusercontent.com/haskell-servant/servant/master/servant.png)
66
7−Generate API docs for your *servant* webservice.
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**.
88
99## Example
1010
example/greet.hs+5
@@ -39,6 +39,11 @@ instance ToParam (QueryParam "capital" Bool) where
3939instance ToSample Greet where
4040 toSample = Just $ Greet "Hello, haskeller!"
4141
42+ toSamples =
43+ [ ("If you use ?capital=true", Greet "HELLO, HASKELLER")
44+ , ("If you use ?capital=false", Greet "Hello, haskeller")
45+ ]
46+
4247-- API specification
4348type TestApi =
4449 -- GET /hello/:name?capital={true, false} returns a Greet as JSON
example/greet.md+27−12
@@ -1,8 +1,7 @@
1−
21POST /greet
32-----------
43
5−**Request Body**:
4+**Request Body**:
65
76``` javascript
87{
@@ -10,50 +9,66 @@ POST /greet
109}
1110```
1211
13−**Response**:
12+**Response**:
1413
1514 - Status code 201
16− - Response body as below.
15+ - If you use ?capital=true
1716
1817``` javascript
1918{
20− "msg": "Hello, haskeller!"
19+ "msg": "HELLO, HASKELLER"
20+}
21+```
22+
23+ - If you use ?capital=false
24+
25+``` javascript
26+{
27+ "msg": "Hello, haskeller"
2128}
2229```
2330
2431GET /hello/:name
2532----------------
2633
27−**Captures**:
34+**Captures**:
2835
2936- *name*: name of the person to greet
3037
31−**GET Parameters**:
38+**GET Parameters**:
3239
3340 - capital
3441 - **Values**: *true, false*
3542 - **Description**: Get the greeting message in uppercase (true) or not (false). Default is false.
3643
3744
38−**Response**:
45+**Response**:
3946
4047 - Status code 200
41− - Response body as below.
48+ - If you use ?capital=true
4249
4350``` javascript
4451{
45− "msg": "Hello, haskeller!"
52+ "msg": "HELLO, HASKELLER"
53+}
54+```
55+
56+ - If you use ?capital=false
57+
58+``` javascript
59+{
60+ "msg": "Hello, haskeller"
4661}
4762```
4863
4964DELETE /greet/:greetid
5065----------------------
5166
52−**Captures**:
67+**Captures**:
5368
5469- *greetid*: identifier of the greet msg to remove
5570
56−**Response**:
71+**Response**:
5772
5873 - Status code 204
5974 - No response body
servant-docs.cabal+5−2
@@ -1,5 +1,5 @@
11name: servant-docs
2−version: 0.2.1
2+version: 0.3
33synopsis: generate API docs for your servant webservice
44description:
55 Library for generating API docs from a servant API definition.
@@ -9,13 +9,16 @@ license: BSD3
99license-file: LICENSE
1010author: Alp Mestanogullari, Sönke Hahn, Julian K. Arni
1111maintainer: alpmestan@gmail.com
12−copyright: 2014 Zalora South East Asia Pte Ltd
12+copyright: 2014-2015 Zalora South East Asia Pte Ltd
1313category: Web
1414build-type: Simple
1515cabal-version: >=1.10
1616tested-with: GHC >= 7.8
1717homepage: http://haskell-servant.github.io/
1818Bug-reports: http://github.com/haskell-servant/servant-docs/issues
19+extra-source-files:
20+ CHANGELOG.md
21+ README.md
1922source-repository head
2023 type: git
2124 location: http://github.com/haskell-servant/servant-docs.git
src/Servant/Docs.hs+58−31
@@ -1,10 +1,12 @@
11{-# LANGUAGE TypeFamilies #-}
22{-# LANGUAGE DeriveGeneric #-}
3+{-# LANGUAGE TupleSections #-}
34{-# LANGUAGE TypeOperators #-}
5+{-# LANGUAGE TemplateHaskell #-}
46{-# LANGUAGE FlexibleContexts #-}
57{-# LANGUAGE FlexibleInstances #-}
8+{-# LANGUAGE OverloadedStrings #-}
69{-# LANGUAGE ScopedTypeVariables #-}
7−{-# LANGUAGE TemplateHaskell #-}
810
911-------------------------------------------------------------------------------
1012-- | This module lets you get API docs for free. It lets generate
@@ -83,12 +85,10 @@ module Servant.Docs
8385 ( -- * 'HasDocs' class and key functions
8486 HasDocs(..), docs, markdown
8587
86− {- , -- * Serving the documentation
87− serveDocumentation -}
88−
8988 , -- * Classes you need to implement for your types
9089 ToSample(..)
9190 , sampleByteString
91+ , sampleByteStrings
9292 , ToParam(..)
9393 , ToCapture(..)
9494
@@ -99,7 +99,7 @@ module Servant.Docs
9999 , DocCapture(..), capSymbol, capDesc
100100 , DocQueryParam(..), ParamKind(..), paramName, paramValues, paramDesc, paramKind
101101 , Response, respStatus, respBody, defResponse
102− , Action, captures, params, rqbody, response, defAction
102+ , Action, captures, headers, params, rqbody, response, defAction
103103 , single
104104
105105 , -- * Useful modules when defining your doc printers
@@ -114,6 +114,7 @@ import Data.ByteString.Lazy.Char8 (ByteString)
114114import Data.Hashable
115115import Data.HashMap.Strict (HashMap)
116116import Data.List
117+import Data.Maybe (listToMaybe)
117118import Data.Monoid
118119import Data.Proxy
119120import Data.Text (Text, pack, unpack)
@@ -123,6 +124,7 @@ import GHC.TypeLits
123124import Servant.API
124125
125126import qualified Data.HashMap.Strict as HM
127+import qualified Data.Text as T
126128
127129-- | Supported HTTP request methods
128130data Method = DocDELETE -- ^ the DELETE method
@@ -148,19 +150,26 @@ instance Hashable Method
148150-- @
149151-- λ> 'defEndpoint'
150152-- GET /
151−-- λ> 'defEndpoint' & 'path' '<>~' "foo"
153+-- λ> 'defEndpoint' & 'path' '<>~' ["foo"]
152154-- GET /foo
153−-- λ> 'defEndpoint' & 'path' '<>~' "foo" & 'method' '.~' 'DocPOST'
155+-- λ> 'defEndpoint' & 'path' '<>~' ["foo"] & 'method' '.~' 'DocPOST'
154156-- POST /foo
155157-- @
156158data Endpoint = Endpoint
157− { _path :: String -- type collected
158− , _method :: Method -- type collected
159+ { _path :: [String] -- type collected
160+ , _method :: Method -- type collected
159161 } deriving (Eq, Generic)
160162
161163instance Show Endpoint where
162164 show (Endpoint p m) =
163− show m ++ " " ++ p
165+ show m ++ " " ++ showPath p
166+
167+-- |
168+-- Render a path as a '/'-delimited string
169+--
170+showPath :: [String] -> String
171+showPath [] = "/"
172+showPath ps = concatMap ('/' :) ps
164173
165174-- | An 'Endpoint' whose path is `"/"` and whose method is 'DocGET'
166175--
@@ -169,13 +178,13 @@ instance Show Endpoint where
169178-- @
170179-- λ> 'defEndpoint'
171180-- GET /
172−-- λ> 'defEndpoint' & 'path' '<>~' "foo"
181+-- λ> 'defEndpoint' & 'path' '<>~' ["foo"]
173182-- GET /foo
174−-- λ> 'defEndpoint' & 'path' '<>~' "foo" & 'method' '.~' 'DocPOST'
183+-- λ> 'defEndpoint' & 'path' '<>~' ["foo"] & 'method' '.~' 'DocPOST'
175184-- POST /foo
176185-- @
177186defEndpoint :: Endpoint
178−defEndpoint = Endpoint "/" DocGET
187+defEndpoint = Endpoint [] DocGET
179188
180189instance Hashable Endpoint
181190
@@ -226,12 +235,12 @@ data ParamKind = Normal | List | Flag
226235-- Can be tweaked with two lenses.
227236--
228237-- > λ> defResponse
229−-- > Response {_respStatus = 200, _respBody = Nothing}
230−-- > λ> defResponse & respStatus .~ 204 & respBody .~ Just "[]"
231−-- > Response {_respStatus = 204, _respBody = Just "[]"}
238+-- > Response {_respStatus = 200, _respBody = []}
239+-- > λ> defResponse & respStatus .~ 204 & respBody .~ [("If everything goes well", "{ \"status\": \"ok\" }")]
240+-- > Response {_respStatus = 204, _respBody = [("If everything goes well", "{ \"status\": \"ok\" }")]}
232241data Response = Response
233242 { _respStatus :: Int
234− , _respBody :: Maybe ByteString
243+ , _respBody :: [(Text, ByteString)]
235244 } deriving (Eq, Show)
236245
237246-- | Default response: status code 200, no response body.
@@ -243,7 +252,7 @@ data Response = Response
243252-- > λ> defResponse & respStatus .~ 204 & respBody .~ Just "[]"
244253-- > Response {_respStatus = 204, _respBody = Just "[]"}
245254defResponse :: Response
246−defResponse = Response 200 Nothing
255+defResponse = Response 200 []
247256
248257-- | A datatype that represents everything that can happen
249258-- at an endpoint, with its lenses:
@@ -327,15 +336,29 @@ class HasDocs layout where
327336-- > toSample = Just g
328337-- >
329338-- > where g = Greet "Hello, haskeller!"
339+--
340+-- You can also instantiate this class using 'toSamples' instead of
341+-- 'toSample': it lets you specify different responses along with
342+-- some context (as 'Text') that explains when you're supposed to
343+-- get the corresponding response.
330344class ToJSON a => ToSample a where
345+ {-# MINIMAL (toSample | toSamples) #-}
331346 toSample :: Maybe a
347+ toSample = fmap snd $ listToMaybe samples
348+ where samples = toSamples :: [(Text, a)]
332349
333−instance ToSample () where
334− toSample = Just ()
350+ toSamples :: [(Text, a)]
351+ toSamples = maybe [] (return . ("",)) s
352+ where s = toSample :: Maybe a
335353
336−sampleByteString :: forall a . ToSample a => Proxy a -> Maybe ByteString
354+sampleByteString :: forall a. ToSample a => Proxy a -> Maybe ByteString
337355sampleByteString Proxy = fmap encodePretty (toSample :: Maybe a)
338356
357+sampleByteStrings :: forall a. ToSample a => Proxy a -> [(Text, ByteString)]
358+sampleByteStrings Proxy = samples & traverse._2 %~ encodePretty
359+
360+ where samples = toSamples :: [(Text, a)]
361+
339362-- | The class that helps us automatically get documentation
340363-- for GET parameters.
341364--
@@ -376,7 +399,7 @@ markdown = unlines . concat . map (uncurry printEndpoint) . HM.toList
376399 responseStr (action ^. response) ++
377400 []
378401
379− where str = show (endpoint^.method) ++ " " ++ endpoint^.path
402+ where str = show (endpoint^.method) ++ " " ++ showPath (endpoint^.path)
380403 len = length str
381404
382405 capturesStr :: [DocCapture] -> [String]
@@ -441,9 +464,13 @@ markdown = unlines . concat . map (uncurry printEndpoint) . HM.toList
441464 "**Response**: " :
442465 "" :
443466 (" - Status code " ++ show (resp ^. respStatus)) :
444− (resp ^. respBody &
445− maybe [" - No response body\n"]
446− (\b -> " - Response body as below." : jsonStr b))
467+ bodies
468+
469+ where bodies = case resp ^. respBody of
470+ [] -> [" - No response body\n"]
471+ [("", r)] -> " - Response body as below." : jsonStr r
472+ xs ->
473+ concatMap (\(ctx, r) -> (" - " <> T.unpack ctx) : jsonStr r) xs
447474
448475-- * Instances
449476
@@ -472,7 +499,7 @@ instance (KnownSymbol sym, ToCapture (Capture sym a), HasDocs sublayout)
472499 captureP = Proxy :: Proxy (Capture sym a)
473500
474501 action' = over captures (|> toCapture captureP) action
475− endpoint' = over path (\p -> p++"/:"++symbolVal symP) endpoint
502+ endpoint' = over path (\p -> p ++ [":" ++ symbolVal symP]) endpoint
476503 symP = Proxy :: Proxy sym
477504
478505
@@ -482,7 +509,7 @@ instance HasDocs Delete where
482509
483510 where endpoint' = endpoint & method .~ DocDELETE
484511
485− action' = action & response.respBody .~ Nothing
512+ action' = action & response.respBody .~ []
486513 & response.respStatus .~ 204
487514
488515instance ToSample a => HasDocs (Get a) where
@@ -490,7 +517,7 @@ instance ToSample a => HasDocs (Get a) where
490517 single endpoint' action'
491518
492519 where endpoint' = endpoint & method .~ DocGET
493− action' = action & response.respBody .~ sampleByteString p
520+ action' = action & response.respBody .~ sampleByteStrings p
494521 p = Proxy :: Proxy a
495522
496523instance (KnownSymbol sym, HasDocs sublayout)
@@ -508,7 +535,7 @@ instance ToSample a => HasDocs (Post a) where
508535
509536 where endpoint' = endpoint & method .~ DocPOST
510537
511− action' = action & response.respBody .~ sampleByteString p
538+ action' = action & response.respBody .~ sampleByteStrings p
512539 & response.respStatus .~ 201
513540
514541 p = Proxy :: Proxy a
@@ -519,7 +546,7 @@ instance ToSample a => HasDocs (Put a) where
519546
520547 where endpoint' = endpoint & method .~ DocPUT
521548
522− action' = action & response.respBody .~ sampleByteString p
549+ action' = action & response.respBody .~ sampleByteStrings p
523550 & response.respStatus .~ 200
524551
525552 p = Proxy :: Proxy a
@@ -614,7 +641,7 @@ instance (KnownSymbol path, HasDocs sublayout) => HasDocs (path :> sublayout) wh
614641 docsFor sublayoutP (endpoint', action)
615642
616643 where sublayoutP = Proxy :: Proxy sublayout
617− endpoint' = endpoint & path <>~ symbolVal pa
644+ endpoint' = endpoint & path <>~ [symbolVal pa]
618645 pa = Proxy :: Proxy path
619646
620647{-