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