on a7c3880 help sign in
servant/doc/tutorial/client.lhs
150 lines 5.2 kB history raw
1---
2title: Deriving Haskell functions to query an API
3toc: true
4---
6While defining handlers that serve an API has a lot to it, querying an API is simpler: we do not care about what happens inside the webserver, we just need to know how to talk to it and get a response back. Except that we usually have to write the querying functions by hand because the structure of the API isn't a first class citizen and can't be inspected to generate a bunch of client-side functions.
8*servant* however has a way to inspect API, because APIs are just Haskell types and (GHC) Haskell lets us do quite a few things with types. In the same way that we look at an API type to deduce the types the handlers should have, we can inspect the structure of the API to *derive* Haskell functions that take one argument for each occurence of `Capture`, `ReqBody`, `QueryParam`
9and friends. By *derive*, we mean that there's no code generation involved, the functions are defined just by the structure of the API type.
11The source for this tutorial section is a literate haskell file, so first we
12need to have some language extensions and imports:
14``` haskell
15{-# LANGUAGE DataKinds #-}
16{-# LANGUAGE DeriveGeneric #-}
17{-# LANGUAGE TypeOperators #-}
19module Client where
21import Control.Monad.Trans.Either
22import Data.Aeson
23import Data.Proxy
24import GHC.Generics
25import Servant.API
26import Servant.Client
27```
29Also, we need examples for some domain specific data types:
31``` haskell
32data Position = Position
33 { x :: Int
34 , y :: Int
35 } deriving (Show, Generic)
37instance FromJSON Position
39newtype HelloMessage = HelloMessage { msg :: String }
40 deriving (Show, Generic)
42instance FromJSON HelloMessage
44data ClientInfo = ClientInfo
45 { clientName :: String
46 , clientEmail :: String
47 , clientAge :: Int
48 , clientInterestedIn :: [String]
49 } deriving Generic
51instance ToJSON ClientInfo
53data Email = Email
54 { from :: String
55 , to :: String
56 , subject :: String
57 , body :: String
58 } deriving (Show, Generic)
60instance FromJSON Email
61```
63Enough chitchat, let's see an example. Consider the following API type from the previous section:
65``` haskell
66type API = "position" :> Capture "x" Int :> Capture "y" Int :> Get '[JSON] Position
67 :<|> "hello" :> QueryParam "name" String :> Get '[JSON] HelloMessage
68 :<|> "marketing" :> ReqBody '[JSON] ClientInfo :> Post '[JSON] Email
69```
71What we are going to get with *servant-client* here is 3 functions, one to query each endpoint:
73``` haskell
74position :: Int -- ^ value for "x"
75 -> Int -- ^ value for "y"
76 -> EitherT ServantError IO Position
78hello :: Maybe String -- ^ an optional value for "name"
79 -> EitherT ServantError IO HelloMessage
81marketing :: ClientInfo -- ^ value for the request body
82 -> EitherT ServantError IO Email
83```
85Each function makes available as an argument any value that the response may depend on, as evidenced in the API type. How do we get these functions? Just give a `Proxy` to your API and a host to make the requests to:
87``` haskell
88api :: Proxy API
89api = Proxy
91position :<|> hello :<|> marketing = client api (BaseUrl Http "localhost" 8081)
92```
94As you can see in the code above, we just "pattern match our way" to these functions. If we try to derive less or more functions than there are endpoints in the API, we obviously get an error. The `BaseUrl` value there is just:
96``` haskell ignore
97-- | URI scheme to use
98data Scheme =
99 Http -- ^ http://
100 | Https -- ^ https://
101 deriving
103-- | Simple data type to represent the target of HTTP requests
104-- for servant's automatically-generated clients.
105data BaseUrl = BaseUrl
106 { baseUrlScheme :: Scheme -- ^ URI scheme to use
107 , baseUrlHost :: String -- ^ host (eg "haskell.org")
108 , baseUrlPort :: Int -- ^ port (eg 80)
109 }
110```
112That's it. Let's now write some code that uses our client functions.
114``` haskell
115queries :: EitherT ServantError IO (Position, HelloMessage, Email)
116queries = do
117 pos <- position 10 10
118 msg <- hello (Just "servant")
119 em <- marketing (ClientInfo "Alp" "alp@foo.com" 26 ["haskell", "mathematics"])
120 return (pos, msg, em)
122run :: IO ()
123run = do
124 res <- runEitherT queries
125 case res of
126 Left err -> putStrLn $ "Error: " ++ show err
127 Right (pos, msg, em) -> do
128 print pos
129 print msg
130 print em
131```
133You can now run `dist/build/tutorial/tutorial 8` (the server) and
134`dist/build/t8-main/t8-main` (the client) to see them both in action.
136``` bash
137 $ dist/build/tutorial/tutorial 8
138 # and in another terminal:
139 $ dist/build/t8-main/t8-main
140 Position {x = 10, y = 10}
141 HelloMessage {msg = "Hello, servant"}
142 Email {from = "great@company.com", to = "alp@foo.com", subject = "Hey Alp, we miss you!", body = "Hi Alp,\n\nSince you've recently turned 26, have you checked out our latest haskell, mathematics products? Give us a visit!"}
143```
145The types of the arguments for the functions are the same as for (server-side) request handlers. You now know how to use *servant-client*!
147<div style="text-align: center;">
148 <p><a href="/tutorial/server.html">Previous page: Serving an API</a></p>
149 <p><a href="/tutorial/javascript.html">Next page: Generating javascript functions to query an API</a></p>
150</div>