git.iko.soy/typeable/servant
on aa64d7a help sign in
83 lines 2.6 kB history raw
1{-# LANGUAGE DataKinds #-}
2{-# LANGUAGE DeriveGeneric #-}
3{-# LANGUAGE TypeOperators #-}
4{-# LANGUAGE FlexibleInstances #-}
5{-# LANGUAGE OverloadedStrings #-}
6{-# OPTIONS_GHC -fno-warn-orphans #-}
7import Data.Aeson
8import Data.Proxy
9import Data.Text(Text)
10import GHC.Generics
11import Servant.API
12import Servant.Docs
14-- * Example
16-- | A greet message data type
17newtype Greet = Greet { msg :: Text }
18 deriving (Generic, Show)
20instance FromJSON Greet
21instance ToJSON Greet
23-- We add some useful annotations to our captures,
24-- query parameters and request body to make the docs
25-- really helpful.
26instance ToCapture (Capture "name" Text) where
27 toCapture _ = DocCapture "name" "name of the person to greet"
29instance ToCapture (Capture "greetid" Text) where
30 toCapture _ = DocCapture "greetid" "identifier of the greet msg to remove"
32instance ToParam (QueryParam "capital" Bool) where
33 toParam _ =
34 DocQueryParam "capital"
35 ["true", "false"]
36 "Get the greeting message in uppercase (true) or not (false). Default is false."
37 Normal
39instance ToSample Greet where
40 toSample = Just $ Greet "Hello, haskeller!"
42 toSamples =
43 [ ("If you use ?capital=true", Greet "HELLO, HASKELLER")
44 , ("If you use ?capital=false", Greet "Hello, haskeller")
45 ]
47instance ToIntro "on proper introductions" where
48 toIntro _ = DocIntro "On proper introductions." -- The title
49 [ "Hello there."
50 , "As documentation is usually written for humans, it's often useful \
51 \to introduce concepts with a few words." ] -- Elements are paragraphs
53instance ToIntro "on zebras" where
54 toIntro _ = DocIntro "This title is below the last"
55 [ "You'll also note that multiple intros are possible." ]
58-- API specification
59type TestApi =
60 -- GET /hello/:name?capital={true, false} returns a Greet as JSON
61 "hello" :> Capture "name" Text :> QueryParam "capital" Bool :> Get Greet
63 -- POST /greet with a Greet as JSON in the request body,
64 -- returns a Greet as JSON
65 :<|> "greet" :> ReqBody Greet :> Post Greet
67 -- DELETE /greet/:greetid
68 :<|> "greet" :> Capture "greetid" Text :> Delete
70type IntroducedApi =
71 Intro "on proper introductions" :> Intro "on zebras" :> TestApi
73introducedApi :: Proxy IntroducedApi
74introducedApi = Proxy
76-- Generate the data that lets us have API docs. This
77-- is derived from the type as well as from
78-- the 'ToCapture', 'ToParam' and 'ToSample' instances from above.
79docsGreet :: API
80docsGreet = docs introducedApi
82main :: IO ()
83main = putStrLn $ markdown docsGreet