2title: Deriving Haskell functions to query an API
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:
15{-# LANGUAGE DataKinds #-}
16{-# LANGUAGE DeriveGeneric #-}
17{-# LANGUAGE TypeOperators #-}
21import Control.Monad.Trans.Either
29Also, we need examples for some domain specific data types:
32data Position = Position
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
48 , clientInterestedIn :: [String]
51instance ToJSON ClientInfo
58 } deriving (Show, Generic)
60instance FromJSON Email
63Enough chitchat, let's see an example. Consider the following API type from the previous section:
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
71What we are going to get with *servant-client* here is 3 functions, one to query each endpoint:
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
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:
91position :<|> hello :<|> marketing = client api (BaseUrl Http "localhost" 8081)
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:
100 | Https -- ^ https://
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)
112That's it. Let's now write some code that uses our client functions.
115queries :: EitherT ServantError IO (Position, HelloMessage, Email)
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)
124 res <- runEitherT queries
126 Left err -> putStrLn $ "Error: " ++ show err
127 Right (pos, msg, em) -> do
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.
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!"}
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>
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list