on e1463cd help sign in
servant/doc/tutorial/Client.lhs
156 lines 5.4 kB history raw
1# Querying an API
3While 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.
5**servant** however has a way to inspect APIs, 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`
6and friends. By *derive*, we mean that there's no code generation involved, the functions are defined just by the structure of the API type.
8The source for this tutorial section is a literate haskell file, so first we
9need to have some language extensions and imports:
11``` haskell
12{-# LANGUAGE DataKinds #-}
13{-# LANGUAGE DeriveGeneric #-}
14{-# LANGUAGE TypeOperators #-}
16module Client where
18import Control.Monad.Trans.Except
19import Data.Aeson
20import Data.Proxy
21import GHC.Generics
22import Network.HTTP.Client (Manager, newManager, defaultManagerSettings)
23import Servant.API
24import Servant.Client
25import System.IO.Unsafe
26```
28Also, we need examples for some domain specific data types:
30``` haskell
31data Position = Position
32 { x :: Int
33 , y :: Int
34 } deriving (Show, Generic)
36instance FromJSON Position
38newtype HelloMessage = HelloMessage { msg :: String }
39 deriving (Show, Generic)
41instance FromJSON HelloMessage
43data ClientInfo = ClientInfo
44 { clientName :: String
45 , clientEmail :: String
46 , clientAge :: Int
47 , clientInterestedIn :: [String]
48 } deriving Generic
50instance ToJSON ClientInfo
52data Email = Email
53 { from :: String
54 , to :: String
55 , subject :: String
56 , body :: String
57 } deriving (Show, Generic)
59instance FromJSON Email
60```
62Enough chitchat, let's see an example. Consider the following API type from the previous section:
64``` haskell
65type API = "position" :> Capture "x" Int :> Capture "y" Int :> Get '[JSON] Position
66 :<|> "hello" :> QueryParam "name" String :> Get '[JSON] HelloMessage
67 :<|> "marketing" :> ReqBody '[JSON] ClientInfo :> Post '[JSON] Email
68```
70What we are going to get with **servant-client** here is 3 functions, one to query each endpoint:
72``` haskell
73position :: Int -- ^ value for "x"
74 -> Int -- ^ value for "y"
75 -> ExceptT ServantError IO Position
77hello :: Maybe String -- ^ an optional value for "name"
78 -> ExceptT ServantError IO HelloMessage
80marketing :: ClientInfo -- ^ value for the request body
81 -> ExceptT ServantError IO Email
82```
84Each function makes available as an argument any value that the response may
85depend on, as evidenced in the API type. How do we get these functions? By calling
86the function `client`. It takes three arguments:
88- a `Proxy` to your API,
89- a `BaseUrl`, consisting of the protocol, the host, the port and an optional subpath --
90 this basically tells `client` where the service that you want to query is hosted,
91- a `Manager`, (from [http-client](http://hackage.haskell.org/package/http-client))
92which manages http connections.
94``` haskell
95api :: Proxy API
96api = Proxy
98{-# NOINLINE __manager #-}
99__manager :: Manager
100__manager = unsafePerformIO $ newManager defaultManagerSettings
102position :<|> hello :<|> marketing =
103 client api (BaseUrl Http "localhost" 8081 "") __manager
104```
106(Yes, the usage of `unsafePerformIO` is very ugly, we know. Hopefully soon it'll
107be possible to do without.)
109As 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:
111``` haskell ignore
112-- | URI scheme to use
113data Scheme =
114 Http -- ^ http://
115 | Https -- ^ https://
116 deriving
118-- | Simple data type to represent the target of HTTP requests
119-- for servant's automatically-generated clients.
120data BaseUrl = BaseUrl
121 { baseUrlScheme :: Scheme -- ^ URI scheme to use
122 , baseUrlHost :: String -- ^ host (eg "haskell.org")
123 , baseUrlPort :: Int -- ^ port (eg 80)
124 }
125```
127That's it. Let's now write some code that uses our client functions.
129``` haskell
130queries :: ExceptT ServantError IO (Position, HelloMessage, Email)
131queries = do
132 pos <- position 10 10
133 message <- hello (Just "servant")
134 em <- marketing (ClientInfo "Alp" "alp@foo.com" 26 ["haskell", "mathematics"])
135 return (pos, message, em)
137run :: IO ()
138run = do
139 res <- runExceptT queries
140 case res of
141 Left err -> putStrLn $ "Error: " ++ show err
142 Right (pos, message, em) -> do
143 print pos
144 print message
145 print em
146```
148Here's the output of the above code running against the appropriate server:
150``` bash
151Position {x = 10, y = 10}
152HelloMessage {msg = "Hello, servant"}
153Email {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!"}
154```
156The types of the arguments for the functions are the same as for (server-side) request handlers. You now know how to use **servant-client**!