git.iko.soy/typeable/servant
on v0.7 help sign in
150 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 (ExceptT, runExceptT)
19import Data.Aeson
20import Data.Proxy
21import GHC.Generics
22import Network.HTTP.Client (Manager, newManager, defaultManagerSettings)
23import Servant.API
24import Servant.Client
25```
27Also, we need examples for some domain specific data types:
29``` haskell
30data Position = Position
31 { x :: Int
32 , y :: Int
33 } deriving (Show, Generic)
35instance FromJSON Position
37newtype HelloMessage = HelloMessage { msg :: String }
38 deriving (Show, Generic)
40instance FromJSON HelloMessage
42data ClientInfo = ClientInfo
43 { clientName :: String
44 , clientEmail :: String
45 , clientAge :: Int
46 , clientInterestedIn :: [String]
47 } deriving Generic
49instance ToJSON ClientInfo
51data Email = Email
52 { from :: String
53 , to :: String
54 , subject :: String
55 , body :: String
56 } deriving (Show, Generic)
58instance FromJSON Email
59```
61Enough chitchat, let's see an example. Consider the following API type from the previous section:
63``` haskell
64type API = "position" :> Capture "x" Int :> Capture "y" Int :> Get '[JSON] Position
65 :<|> "hello" :> QueryParam "name" String :> Get '[JSON] HelloMessage
66 :<|> "marketing" :> ReqBody '[JSON] ClientInfo :> Post '[JSON] Email
67```
69What we are going to get with **servant-client** here is 3 functions, one to query each endpoint:
71``` haskell
72position :: Int -- ^ value for "x"
73 -> Int -- ^ value for "y"
74 -> Manager -- ^ the HTTP client to use
75 -> BaseUrl -- ^ the URL at which the API can be found
76 -> ExceptT ServantError IO Position
78hello :: Maybe String -- ^ an optional value for "name"
79 -> Manager -- ^ the HTTP client to use
80 -> BaseUrl -- ^ the URL at which the API can be found
81 -> ExceptT ServantError IO HelloMessage
83marketing :: ClientInfo -- ^ value for the request body
84 -> Manager -- ^ the HTTP client to use
85 -> BaseUrl -- ^ the URL at which the API can be found
86 -> ExceptT ServantError IO Email
87```
89Each function makes available as an argument any value that the response may
90depend on, as evidenced in the API type. How do we get these functions? By calling
91the function `client`. It takes one argument:
93- a `Proxy` to your API,
95``` haskell
96api :: Proxy API
97api = Proxy
99position :<|> hello :<|> marketing = client api
100```
102As 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:
104``` haskell ignore
105-- | URI scheme to use
106data Scheme =
107 Http -- ^ http://
108 | Https -- ^ https://
109 deriving
111-- | Simple data type to represent the target of HTTP requests
112-- for servant's automatically-generated clients.
113data BaseUrl = BaseUrl
114 { baseUrlScheme :: Scheme -- ^ URI scheme to use
115 , baseUrlHost :: String -- ^ host (eg "haskell.org")
116 , baseUrlPort :: Int -- ^ port (eg 80)
117 }
118```
120That's it. Let's now write some code that uses our client functions.
122``` haskell
123queries :: Manager -> BaseUrl -> ExceptT ServantError IO (Position, HelloMessage, Email)
124queries manager baseurl = do
125 pos <- position 10 10 manager baseurl
126 message <- hello (Just "servant") manager baseurl
127 em <- marketing (ClientInfo "Alp" "alp@foo.com" 26 ["haskell", "mathematics"]) manager baseurl
128 return (pos, message, em)
130run :: IO ()
131run = do
132 manager <- newManager defaultManagerSettings
133 res <- runExceptT (queries manager (BaseUrl Http "localhost" 8081 ""))
134 case res of
135 Left err -> putStrLn $ "Error: " ++ show err
136 Right (pos, message, em) -> do
137 print pos
138 print message
139 print em
140```
142Here's the output of the above code running against the appropriate server:
144``` bash
145Position {x = 10, y = 10}
146HelloMessage {msg = "Hello, servant"}
147Email {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!"}
148```
150The types of the arguments for the functions are the same as for (server-side) request handlers. You now know how to use **servant-client**!