2014-12-08 11:10:51 +01:00
|
|
|
# servant-client
|
|
|
|
|
|
|
|
![servant](https://raw.githubusercontent.com/haskell-servant/servant/master/servant.png)
|
|
|
|
|
2015-02-06 09:34:59 +01:00
|
|
|
This library lets you automatically derive Haskell functions that let you query each endpoint of a *servant* webservice.
|
2014-12-08 11:10:51 +01:00
|
|
|
|
|
|
|
## Example
|
|
|
|
|
|
|
|
``` haskell
|
2018-04-18 15:01:42 +02:00
|
|
|
{-# LANGUAGE DataKinds #-}
|
|
|
|
{-# LANGUAGE TypeOperators #-}
|
|
|
|
|
|
|
|
import Data.Proxy
|
|
|
|
import Data.Text
|
|
|
|
import Network.HTTP.Client (newManager, defaultManagerSettings)
|
|
|
|
import Servant.API
|
|
|
|
import Servant.Client
|
|
|
|
|
|
|
|
|
|
|
|
type Book = Text
|
|
|
|
|
2015-05-14 00:52:37 +02:00
|
|
|
type MyApi = "books" :> Get '[JSON] [Book] -- GET /books
|
2018-04-18 15:01:42 +02:00
|
|
|
:<|> "books" :> ReqBody '[JSON] Book :> Post '[JSON] Book -- POST /books
|
2014-12-08 11:10:51 +01:00
|
|
|
|
|
|
|
myApi :: Proxy MyApi
|
|
|
|
myApi = Proxy
|
|
|
|
|
|
|
|
-- 'client' allows you to produce operations to query an API from a client.
|
2018-04-18 15:01:42 +02:00
|
|
|
postNewBook :: Book -> ClientM Book
|
|
|
|
getAllBooks :: ClientM [Book]
|
2016-05-25 17:33:18 +02:00
|
|
|
(getAllBooks :<|> postNewBook) = client myApi
|
2018-04-18 15:01:42 +02:00
|
|
|
|
|
|
|
|
|
|
|
main :: IO ()
|
|
|
|
main = do
|
|
|
|
manager' <- newManager defaultManagerSettings
|
|
|
|
res <- runClientM getAllBooks (mkClientEnv manager' (BaseUrl Http "localhost" 8081 ""))
|
|
|
|
case res of
|
|
|
|
Left err -> putStrLn $ "Error: " ++ show err
|
|
|
|
Right books -> print books
|
2015-04-20 15:38:26 +02:00
|
|
|
```
|