3While defining handlers that [serve an API](Server.lhs) 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. That said, 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 the 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 occurrence of `Capture`, `ReqBody`, `QueryParam`
6and friends (see [the tutorial introduction](ApiType.lhs) for an overview). 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 need to have some language extensions and imports:
11{-# LANGUAGE DataKinds #-}
12{-# LANGUAGE DeriveGeneric #-}
13{-# LANGUAGE TypeOperators #-}
20import Network.HTTP.Client (newManager, defaultManagerSettings)
25Also, we need examples for some domain specific data types:
28data Position = Position
31 } deriving (Show, Generic)
33instance FromJSON Position
35newtype HelloMessage = HelloMessage { msg :: String }
36 deriving (Show, Generic)
38instance FromJSON HelloMessage
40data ClientInfo = ClientInfo
41 { clientName :: String
42 , clientEmail :: String
44 , clientInterestedIn :: [String]
47instance ToJSON ClientInfo
54 } deriving (Show, Generic)
56instance FromJSON Email
59Enough chitchat, let's see an example. Consider the following API type from the previous section:
62type API = "position" :> Capture "x" Int :> Capture "y" Int :> Get '[JSON] Position
63 :<|> "hello" :> QueryParam "name" String :> Get '[JSON] HelloMessage
64 :<|> "marketing" :> ReqBody '[JSON] ClientInfo :> Post '[JSON] Email
67What we are going to get with **servant-client** here is three functions, one to query each endpoint:
70position :: Int -- ^ value for "x"
71 -> Int -- ^ value for "y"
74hello :: Maybe String -- ^ an optional value for "name"
75 -> ClientM HelloMessage
77marketing :: ClientInfo -- ^ value for the request body
81Each function makes available as an argument any value that the response may
82depend on, as evidenced in the API type. How do we get these functions? By calling
83the function `client`. It takes one argument:
85- a `Proxy` to your API,
91position :<|> hello :<|> marketing = client api
94`client api` returns client functions for our _entire_ API, combined with `:<|>`, which we can pattern match on as above. You could say `client` "calculates" the correct type and number of client functions for the API type it is given (via a `Proxy`), as well as their implementations.
96If you have an `EmptyAPI` in your API, servant-client will hand you a value of
97type `EmptyClient` in the corresponding slot, where `data EmptyClient =
98EmptyClient`, as a way to indicate that you can't do anything useful with it.
101type API' = API :<|> EmptyAPI
106(position' :<|> hello' :<|> marketing') :<|> EmptyClient = client api'
110-- | URI scheme to use
113 | Https -- ^ https://
116-- | Simple data type to represent the target of HTTP requests
117-- for servant's automatically-generated clients.
118data BaseUrl = BaseUrl
119 { baseUrlScheme :: Scheme -- ^ URI scheme to use
120 , baseUrlHost :: String -- ^ host (eg "haskell.org")
121 , baseUrlPort :: Int -- ^ port (eg 80)
122 , baseUrlPath :: String -- ^ path (eg "/a/b/c")
126That's it. Let's now write some code that uses our client functions.
129queries :: ClientM (Position, HelloMessage, Email)
131 pos <- position 10 10
132 message <- hello (Just "servant")
133 em <- marketing (ClientInfo "Alp" "alp@foo.com" 26 ["haskell", "mathematics"])
134 return (pos, message, em)
138 manager' <- newManager defaultManagerSettings
139 res <- runClientM queries (ClientEnv manager' (BaseUrl Http "localhost" 8081 ""))
141 Left err -> putStrLn $ "Error: " ++ show err
142 Right (pos, message, em) -> do
148Here's the output of the above code running against the appropriate server:
151Position {xCoord = 10, yCoord = 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!"}
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**!
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