git.iko.soy/typeable/servant
on f76c729 help sign in
72 lines 1.9 kB history raw
1{-# LANGUAGE DataKinds #-}
2{-# LANGUAGE PolyKinds #-}
3{-# LANGUAGE TypeFamilies #-}
4{-# LANGUAGE DeriveGeneric #-}
5{-# LANGUAGE TypeOperators #-}
6{-# LANGUAGE OverloadedStrings #-}
8import Data.Aeson
9import Data.Monoid
10import Data.Proxy
11import Data.Text
12import GHC.Generics
13import Network.Wai
14import Network.Wai.Handler.Warp
16import Servant
18-- * Example
20-- | A greet message data type
21newtype Greet = Greet { _msg :: Text }
22 deriving (Generic, Show)
24instance FromJSON Greet
25instance ToJSON Greet
27-- API specification
28type TestApi =
29 -- GET /hello/:name?capital={true, false} returns a Greet as JSON
30 "hello" :> Capture "name" Text :> QueryParam "capital" Bool :> Get '[JSON] Greet
32 -- POST /greet with a Greet as JSON in the request body,
33 -- returns a Greet as JSON
34 :<|> "greet" :> ReqBody '[JSON] Greet :> Post '[JSON] Greet
36 -- DELETE /greet/:greetid
37 :<|> "greet" :> Capture "greetid" Text :> Delete
39testApi :: Proxy TestApi
40testApi = Proxy
42-- Server-side handlers.
43--
44-- There's one handler per endpoint, which, just like in the type
45-- that represents the API, are glued together using :<|>.
46--
47-- Each handler runs in the 'EitherT (Int, String) IO' monad.
48server :: Server TestApi
49server = helloH :<|> postGreetH :<|> deleteGreetH
51 where helloH name Nothing = helloH name (Just False)
52 helloH name (Just False) = return . Greet $ "Hello, " <> name
53 helloH name (Just True) = return . Greet . toUpper $ "Hello, " <> name
55 postGreetH greet = return greet
57 deleteGreetH _ = return ()
59-- Turn the server into a WAI app. 'serve' is provided by servant,
60-- more precisely by the Servant.Server module.
61test :: Application
62test = serve testApi server
64-- Run the server.
65--
66-- 'run' comes from Network.Wai.Handler.Warp
67runTestServer :: Port -> IO ()
68runTestServer port = run port test
70-- Put this all to work!
71main :: IO ()
72main = runTestServer 8001