git.iko.soy/typeable/servant
on v0.13.0.1 help sign in
175 lines 5.7 kB history raw
1# servant-client-ghcjs
3Type safe querying of servant APIs from the browser.
5`servant-client-ghcjs` is much like `servant-client`, as both packages allow you to generate functions that query the endpoints of your servant API. Both packages should feel the same in usage. The big difference lies in how they perform the actual requests. `servant-client` (indirectly) uses your operating system's socket mechanisms, whereas `servant-client-ghcjs` uses your browser's [XHR](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) mechanisms to send requests.
7This guide assumes knowledge of servant. Reading its [documentation](http://haskell-servant.readthedocs.io) is recommended if you're new to the subject.
9## Using servant-client-ghcjs
10`servant-client-ghcjs` should feel familiar if you've worked with `servant-client`.
12Take the following API (taken from the [Querying an API](http://haskell-servant.readthedocs.io/en/stable/tutorial/Client.html) section in the servant documentation)
14```haskell
15{-# LANGUAGE DataKinds #-}
16{-# LANGUAGE DeriveGeneric #-}
17{-# LANGUAGE TypeOperators #-}
19module Main where
21import Data.Aeson
22import Data.Proxy
23import GHC.Generics
24import Servant.API -- From the 'servant' package, to define the API itself
25import Servant.Client.Ghcjs -- To generate client functions
27type API =
28 "position" :> Capture "x" Int :> Capture "y" Int :> Get '[JSON] Position
29 :<|> "hello" :> QueryParam "name" String :> Get '[JSON] HelloMessage
30 :<|> "marketing" :> ReqBody '[JSON] ClientInfo :> Post '[JSON] Email
33-- Data types used in the API
35data Position = Position
36 { xCoord :: Int
37 , yCoord :: Int
38 } deriving (Show, Generic)
40instance FromJSON Position
42newtype HelloMessage = HelloMessage { msg :: String }
43 deriving (Show, Generic)
45instance FromJSON HelloMessage
47data ClientInfo = ClientInfo
48 { clientName :: String
49 , clientEmail :: String
50 , clientAge :: Int
51 , clientInterestedIn :: [String]
52 } deriving Generic
54instance ToJSON ClientInfo
56data Email = Email
57 { from :: String
58 , to :: String
59 , subject :: String
60 , body :: String
61 } deriving (Show, Generic)
63instance FromJSON Email
64```
66Client functions are generated with the `client` function, like with `servant-client`:
68```haskell
69position :: Int
70 -> Int
71 -> ClientM Position
73hello :: Maybe String
74 -> ClientM HelloMessage
76marketing :: ClientInfo
77 -> ClientM Email
79api :: Proxy API
80api = Proxy
82position :<|> hello :<|> marketing = client api
83```
85To run these requests, they only need to be given to `runClientM`. The type of which is as follows:
87```haskell
88runClientM :: ClientM a -> IO (Either ServantError a)
89```
91The requests can then be run as follows:
93```haskell
94main :: IO ()
95main = do
96 ePos <- runClientM $ position 10 20
97 print ePos
99 eHelloMessage <- runClientM $ hello (Just "Servant")
100 print eHelloMessage
102 eEmail <- runClientM $ marketing ClientInfo
103 { clientName = "Servant"
104 , clientEmail = "servant@example.com"
105 , clientAge = 3
106 , clientInterestedIn = ["servant", "haskell", "type safety", "web apps"]
107 }
108 print eEmail
109```
111`runClientM` requires no URL, as it assumes that all requests are meant for the server that served the web page on which the code is being run. It is however possible to call REST APIs from other locations with [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) using `runClientMOrigin`:
113```haskell
114runClientMOrigin :: ClientM a -> ClientEnv -> IO (Either ServantError a)
115```
117Where `ClientEnv` holds a `BaseURL` that tells servant where to send the request to.
119# Common client functions
120Specifically in big applications it can be desirable to have client functions that work for both `servant-client` *and* `servant-client-ghcjs`. Luckily, the common bits of those two packages live in a parent package, called `servant-client-core`. This package holds the tools to create generic client functions. Generating clients this way is a bit different, though, as the client functions need to be generic in the monad `m` that runs the actual requests.
122In the example below, the client functions are put in a data type called `APIClient`, which has `m` as a type parameter. The lowercase `apiClient` constructs this data type, demanding that `m` is indeed a monad that can run requests.
124```haskell
125{-# LANGUAGE FlexibleContexts #-}
126{-# LANGUAGE RecordWildCards #-}
127{-# LANGUAGE ScopedTypeVariables #-}
128{-# LANGUAGE TypeApplications #-}
130...
131import Servant.Client.Core -- From the 'servant-client-core' package
133...
135data APIClient m = APIClient
136 { position :: Int -> Int -> m Position
137 , hello :: Maybe String -> m HelloMessage
138 , marketing :: ClientInfo -> m Email
139 }
141apiClient
142 :: forall m
143 . RunClient m
144 => APIClient m
145apiClient = APIClient { .. }
146 where
147 position
148 :<|> hello
149 :<|> marketing = Proxy @API `clientIn` Proxy @m
150```
152The call site changes slightly too, as the functions now need to be taken from `apiClient`:
154```haskell
155import Servant.Client.Ghcjs
157main :: IO ()
158main = do
159 ePos <- runClientM $ position apiClient 10 20
160 print ePos
161```
163Here's how the requests would be performed using the regular `servant-client` package:
165```haskell
166import Servant.Client
167import Network.HTTP.Client ( newManager, defaultManagerSettings )
169main :: IO ()
170main = do
171 mgr <- newManager defaultManagerSettings
172 let clientBaseUrl = BaseUrl Http "www.example.com" 80 ""
173 ePos <- runClientM (position apiClient 10 20) $ mkClientEnv mgr clientBaseUrl
174 print ePos
175```