req-0.1.0: Easy-to-use, type-safe, expandable, high-level HTTP library

Copyright© 2016 Mark Karpov
LicenseBSD 3 clause
MaintainerMark Karpov <markkarpov@openmailbox.org>
Stabilityexperimental
Portabilityportable
Safe HaskellNone
LanguageHaskell2010

Network.HTTP.Req

Contents

Description

The documentation below is structured in such a way that most important information goes first: you learn how to do HTTP requests, then how to embed them in any monad you have, then it goes on giving you details about less-common things you may want to know about. The documentation is written with sufficient coverage of details and examples, it's designed to be a complete tutorial on its own.

(A modest intro goes here, click on req to start making requests.)

About the library

This is an easy-to-use, type-safe, expandable, high-level HTTP library that just works without any fooling around.

What does the “easy-to-use” phrase mean? It means that the library is designed to be beginner-friendly, so it's simple to add it to your monad stack, intuitive to work with, well-documented, and does not get in your way. Doing HTTP requests is a common task and Haskell library for this should be very approachable and clear to beginners, thus certain compromises were made. For example, one cannot currently modify ManagerSettings of default manager because the library always uses the same implicit global manager for simplicity and maximal connection sharing. There is a way to use your own manager with different settings, but it requires a bit more typing.

“Type-safe” means that the library is protective and eliminates certain class of errors. For example, we have correct-by-construction Urls, it's guaranteed that user does not send request body when using methods like GET or OPTIONS, amount of implicit assumptions is minimized by making user specify his/her intentions in explicit form (for example, it's not possible to avoid specifying body or method of a request). Authentication methods that assume TLS force user to use TLS on type level. The library carefully hides underlying types from lower-level http-client package because it's not safe enough (for example Request is an instance of IsString and if it's malformed, it will blow up at run-time).

“Expandable” refers to the ability of the library to be expanded without ugly hacking. For example, it's possible to define your own HTTP methods, new ways to construct body of request, new authorization options, new ways to actually perform request and how to represent/parse response. As user extends the library to satisfy his/her special needs, the new solutions work just like built-ins. That said, all common cases are covered by the library out-of-the-box.

“High-level” means that there are less details to worry about. The library is a result of my experiences as a Haskell consultant, working for several clients who have very different projects and so the library adapts easily to any particular style of writing Haskell applications. For example, some people prefer throwing exceptions, while others are concerned with purity: just define handleHttpException accordingly when making your monad instance of MonadHttp and it will play seamlessly. Finally, the library cuts boilerplate considerably and helps write concise, easy to read and maintain code.

Using with other libraries

  • You won't need low-level interface of http-client most of the time, but when you do, it's better import it qualified because it has naming conflicts with req.
  • For streaming of large request bodies see companion package req-conduit: https://hackage.haskell.org/package/req-conduit.

Lightweight, no risk solution

The library uses the following mature packages under the hood to guarantee you best experience without bugs or other funny business:

It's important to note that since we leverage well-known libraries that the whole Haskell ecosystem uses, there is no risk in using req, as the machinery for performing requests is the same as with http-conduit and wreq, it's just the API is different.

Synopsis

Making a request

To make an HTTP request you need only one function: req.

req Source #

Arguments

:: (MonadHttp m, HttpMethod method, HttpBody body, HttpResponse response, HttpBodyAllowed (AllowsBody method) (ProvidesBody body)) 
=> method

HTTP method

-> Url scheme

Url — location of resource

-> body

Body of the request

-> Proxy response

A hint how to interpret response

-> Option scheme

Collection of optional parameters

-> m response

Response

Make an HTTP request. The function takes 5 arguments, 4 of which specify required parameters and the final Option argument is a collection of optional parameters.

Let's go through all the arguments first: req method url body response options.

method is an HTTP method such as GET or POST. The documentation has a dedicated section about HTTP methods below.

url is a URL that describes location of resource you want to interact with. It's of type Url (if you click the link it will tell everything about construction of Url things).

body is a body option such as NoReqBody or ReqBodyJson. The tutorial has a section about HTTP bodies, but usage in very straightforward and should be clear from the examples below.

response is a type hint how to make and interpret response of HTTP request, out-of-the-box it can be the following: ignoreResponse, jsonResponse, bsResponse (to get strict ByteString), lbsResponse (to get lazy ByteString), and returnRequest (makes no request, just returns response, used for testing).

Finally options is a Monoid that holds a composite Option for all other optional things like query parameters, headers, non-standard port number, etc. There are quite a few things you can put there, see corresponding section in the documentation. If you don't need anything at all, pass mempty.

Note that if you use req to do all your requests, connection sharing and reuse is done for you automatically.

See the examples below to get on the speed very quickly.

Examples

First, this is a piece of boilerplate that should be in place before you try the examples:

{-# LANGUAGE OverloadedStrings #-}

module Main (main) where

import Control.Exception (throwIO)
import Control.Monad
import Data.Aeson
import Data.Maybe (fromJust)
import Data.Monoid ((<>))
import Data.Text (Text)
import GHC.Generics
import Network.HTTP.Req
import qualified Data.ByteString.Char8 as B

instance MonadHttp IO where
  handleHttpException = throwIO

We will be making requests against the https://httpbin.org service.

Make a GET request, grab 5 random bytes:

main :: IO ()
main = do
  let n :: Int
      n = 5
  bs <- req GET (https "httpbin.org" /: "bytes" /~ n) NoReqBody bsResponse mempty
  B.putStrLn (responseBody bs)

The same, but now we use a query parameter named "seed" to control seed of the generator:

main :: IO ()
main = do
  let n, seed :: Int
      n    = 5
      seed = 100
  bs <- req GET (https "httpbin.org" /: "bytes" /~ n) NoReqBody bsResponse $
    "seed" =: seed
  B.putStrLn (responseBody bs)

POST JSON data and get some info about the POST request:

data MyData = MyData
  { size  :: Int
  , color :: Text
  } deriving (Show, Generic)

instance ToJSON MyData
instance FromJSON MyData

main :: IO ()
main = do
  let myData = MyData
        { size  = 6
        , color = "Green" }
  v <- req POST (https "httpbin.org" /: "post") (ReqBodyJson myData) jsonResponse mempty
  print (responseBody v :: Value)

Sending URL-encoded body:

main :: IO ()
main = do
  let params =
        "foo" =: ("bar" :: Text) <>
        queryFlag "baz"
  response <- req POST (https "httpbin.org" /: "post") (ReqBodyUrlEnc params) jsonResponse mempty
  print (responseBody response :: Value)

Using various optional parameters and URL that is not known in advance:

main :: IO ()
main = do
  -- This is an example of what to do when URL is given dynamically. Of
  -- course in a real application you may not want to use 'fromJust'.
  let (url, options) = fromJust (parseUrlHttps "https://httpbin.org/get?foo=bar")
  response <- req GET url NoReqBody jsonResponse $
    "from" =: (15 :: Int)           <>
    "to"   =: (67 :: Int)           <>
    basicAuth "username" "password" <>
    options                         <> -- contains the ?foo=bar part
    port 443 -- here you can put any port of course
  print (responseBody response :: Value)

withReqManager :: MonadIO m => (Manager -> m a) -> m a Source #

Perform an action using global implicit Manager that the rest of the library uses. This allows to reuse connections that the Manager controls.

Embedding requests into your monad

To use req in your monad, all you need to do is to make the monad an instance of the MonadHttp type class.

When writing a library, keep your API polymorphic in terms of MonadHttp, only define instance of MonadHttp in final application.

class MonadIO m => MonadHttp m where Source #

A type class for monads that support performing HTTP requests. Typically, you only need to define the handleHttpException method unless you want to tweak HttpConfig.

Minimal complete definition

handleHttpException

Methods

handleHttpException :: HttpException -> m a Source #

This method describes how to deal with HttpException that was caught by the library. One option is to re-throw it if you are OK with exceptions, but if you prefer working with something like MonadError, this is the right place to pass it to throwError.

getHttpConfig :: m HttpConfig Source #

Return HttpConfig to be used when performing HTTP requests. Default implementation returns its def value, which is described in the documentation for the type. Common usage pattern with manually defined getHttpConfig is to return some hard-coded value, or value extracted from MonadReader if a more flexible approach to configuration is desirable.

data HttpConfig Source #

HttpConfig contains general and default settings to be used when making HTTP requests.

Constructors

HttpConfig 

Fields

  • httpConfigProxy :: Maybe Proxy

    Proxy to use. By default values of HTTP_PROXY and HTTPS_PROXY environment variables are respected, this setting overwrites them. Default value: Nothing.

  • httpConfigRedirectCount :: Int

    How many redirects to follow when getting a resource. Default value: 10.

  • httpConfigAltManager :: Maybe Manager

    Alternative Manager to use. Nothing (default value) means that default implicit manager will be used (that's what you want in 99% of cases).

  • httpConfigCheckResponse :: Request -> Response BodyReader -> IO ()

    Function to check the response immediately after receiving the status and headers. This is used for throwing exceptions on non-success status codes by default (set to \_ _ -> return () if this behavior is not desirable). Throwing is better then just returning a request with non-2xx status code because in that case something is wrong and we need a way to short-cut execution. The thrown exception is caught by the library though and is available in handleHttpException.

Instances

Request

Method

The package supports all methods as defined by RFC 2616, and PATCH which is defined by RFC 5789 — that should be enough to talk to RESTful APIs. In some cases, however, you may want to add more methods (e.g. you work with WebDAV https://en.wikipedia.org/wiki/WebDAV); no need to compromise on type safety and hack, it only takes a couple of seconds to define a new method that will works seamlessly, see HttpMethod.

data GET Source #

GET method.

Constructors

GET 

data POST Source #

POST method.

Constructors

POST 

data HEAD Source #

HEAD method.

Constructors

HEAD 

data PUT Source #

PUT method.

Constructors

PUT 

data DELETE Source #

DELETE method. This data type does not allow having request body with DELETE requests, as it should be, however some APIs may expect DELETE requests to have bodies, in that case define your own variation of DELETE method and allow it to have a body.

Constructors

DELETE 

data TRACE Source #

TRACE method.

Constructors

TRACE 

data PATCH Source #

PATCH method.

Constructors

PATCH 

class HttpMethod a where Source #

A type class for types that can be used as an HTTP method. To define a non-standard method, follow this example that defines COPY:

data COPY = COPY

instance HttpMethod COPY where
  type AllowsBody COPY = 'CanHaveBody
  httpMethodName Proxy = "COPY"

Minimal complete definition

httpMethodName

Associated Types

type AllowsBody a :: CanHaveBody Source #

Type function AllowsBody returns type of kind CanHaveBody which tells the rest of the library whether the method can have a body or not. We use the special type CanHaveBody “lifted” into kind instead of Bool to get more user-friendly compiler messages.

Methods

httpMethodName :: Proxy a -> ByteString Source #

Return name of the method as a ByteString.

URL

We use Urls which are correct by construction, see Url. To build a Url from a ByteString, use parseUrlHttp or parseUrlHttps.

data Url scheme Source #

Request's Url. Start constructing your Url with http or https specifying the scheme and host at the same time. Then use the (/~) and (/:) operators to grow path one piece at a time. Every single piece of path will be url(percent)-encoded, so using (/~) and (/:) is the only way to have forward slashes between path segments. This approach makes working with dynamic path segments easy and safe. See examples below how to represent various Urls (make sure the OverloadedStrings language extension is enabled).

Examples

http "httpbin.org"
-- http://httpbin.org
https "httpbin.org"
-- https://httpbin.org
https "httpbin.org" /: "encoding" /: "utf8"
-- https://httpbin.org/encoding/utf8
https "httpbin.org" /: "foo" /: "bar/baz"
-- https://httpbin.org/foo/bar%2Fbaz
https "httpbin.org" /: "bytes" /~ (10 :: Int)
-- https://httpbin.org/bytes/10
https "юникод.рф"
-- https://%D1%8E%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4.%D1%80%D1%84

Instances

Eq (Url scheme) Source # 

Methods

(==) :: Url scheme -> Url scheme -> Bool #

(/=) :: Url scheme -> Url scheme -> Bool #

Typeable Scheme scheme => Data (Url scheme) Source # 

Methods

gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Url scheme -> c (Url scheme) #

gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (Url scheme) #

toConstr :: Url scheme -> Constr #

dataTypeOf :: Url scheme -> DataType #

dataCast1 :: Typeable (* -> *) t => (forall d. Data d => c (t d)) -> Maybe (c (Url scheme)) #

dataCast2 :: Typeable (* -> * -> *) t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (Url scheme)) #

gmapT :: (forall b. Data b => b -> b) -> Url scheme -> Url scheme #

gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Url scheme -> r #

gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Url scheme -> r #

gmapQ :: (forall d. Data d => d -> u) -> Url scheme -> [u] #

gmapQi :: Int -> (forall d. Data d => d -> u) -> Url scheme -> u #

gmapM :: Monad m => (forall d. Data d => d -> m d) -> Url scheme -> m (Url scheme) #

gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Url scheme -> m (Url scheme) #

gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Url scheme -> m (Url scheme) #

Ord (Url scheme) Source # 

Methods

compare :: Url scheme -> Url scheme -> Ordering #

(<) :: Url scheme -> Url scheme -> Bool #

(<=) :: Url scheme -> Url scheme -> Bool #

(>) :: Url scheme -> Url scheme -> Bool #

(>=) :: Url scheme -> Url scheme -> Bool #

max :: Url scheme -> Url scheme -> Url scheme #

min :: Url scheme -> Url scheme -> Url scheme #

Show (Url scheme) Source # 

Methods

showsPrec :: Int -> Url scheme -> ShowS #

show :: Url scheme -> String #

showList :: [Url scheme] -> ShowS #

Generic (Url scheme) Source # 

Associated Types

type Rep (Url scheme) :: * -> * #

Methods

from :: Url scheme -> Rep (Url scheme) x #

to :: Rep (Url scheme) x -> Url scheme #

type Rep (Url scheme) Source # 

http :: Text -> Url Http Source #

Given host name, produce a Url which have “http” as its scheme and empty path. This also sets port to 80.

https :: Text -> Url Https Source #

Given host name, produce a Url which have “https” as its scheme and empty path. This also sets port to 443.

(/~) :: ToHttpApiData a => Url scheme -> a -> Url scheme infixl 5 Source #

Grow given Url appending a single path segment to it. Note that the path segment can be of any type that is an instance of ToHttpApiData.

(/:) :: Url scheme -> Text -> Url scheme infixl 5 Source #

Type-constrained version of (/~) to remove ambiguity in cases when next URL piece is a Text literal.

parseUrlHttp :: ByteString -> Maybe (Url Http, Option scheme) Source #

The parseUrlHttp function provides an alternative method to get Url (possibly with some Options) from a ByteString. This is useful when you are given a URL to query dynamically and don't know it beforehand. The function parses ByteString because it's the correct type to represent a URL, as Url cannot contain characters outside of ASCII range, thus we can consider every character a Word8 value.

This function only parses Url (scheme, host, path) and optional query parameters that are returned as Option. It does not parse method name or authentication info from given ByteString.

parseUrlHttps :: ByteString -> Maybe (Url Https, Option scheme) Source #

Just like parseUrlHttp, but expects “https” scheme.

Body

A number of options for request bodies are available. The Content-Type header is set for you automatically according to body option you use (it's always specified in documentation for given body option). To add your own way to represent request body, see HttpBody.

data NoReqBody Source #

This data type represents empty body of an HTTP request. This is the data type to use with HttpMethods that cannot have a body, as it's the only type for which ProvidesBody returns NoBody.

Using of this body option does not set the Content-Type header.

Constructors

NoReqBody 

newtype ReqBodyJson a Source #

This body option allows to use a JSON object as request body — probably the most popular format right now. Just wrap a data type that is an instance of ToJSON type class and you are done: it will be converted to JSON and inserted as request body.

This body option sets the Content-Type header to "application/json; charset=utf-8" value.

Constructors

ReqBodyJson a 

newtype ReqBodyFile Source #

This body option streams request body from a file. It is expected that the file size does not change during the streaming.

Using of this body option does not set the Content-Type header.

Constructors

ReqBodyFile FilePath 

newtype ReqBodyBs Source #

HTTP request body represented by a strict ByteString.

Using of this body option does not set the Content-Type header.

Constructors

ReqBodyBs ByteString 

newtype ReqBodyLbs Source #

HTTP request body represented by a lazy ByteString.

Using of this body option does not set the Content-Type header.

Constructors

ReqBodyLbs ByteString 

newtype ReqBodyUrlEnc Source #

Form URL-encoded body. This can hold a collection of parameters which are encoded similarly to query parameters at the end of query string, with the only difference that they are stored in request body. The similarity is reflected in the API as well, as you can use the same combinators you would use to add query parameters: (=:) and queryFlag.

This body option sets the Content-Type header to "application/x-www-from-urlencoded" value.

class HttpBody body where Source #

A type class for things that can be interpreted as HTTP RequestBody.

Minimal complete definition

getRequestBody

Methods

getRequestBody :: body -> RequestBody Source #

How to get actual RequestBody.

getRequestContentType :: Proxy body -> Maybe ByteString Source #

This method allows to optionally specify value of Content-Type header that should be used with particular body option. By default it returns Nothing and so Content-Type is not set.

type family ProvidesBody body :: CanHaveBody where ... Source #

The type function recognizes NoReqBody as having NoBody, while any other body option CanHaveBody. This forces user to use NoReqBody with GET method and other methods that should not send a body.

type family HttpBodyAllowed (allowsBody :: CanHaveBody) (providesBody :: CanHaveBody) :: Constraint where ... Source #

This type function allows any HTTP body if method says it CanHaveBody. When method says it should have NoBody, the only body option to use is NoReqBody.

Note: users of GHC 8.0.1 will see slightly more friendly error messages when method does not allow a body and body is provided.

Equations

HttpBodyAllowed NoBody NoBody = () 
HttpBodyAllowed CanHaveBody body = () 
HttpBodyAllowed NoBody CanHaveBody = TypeError (Text "This HTTP method does not allow attaching a request body.") 

Optional parameters

Optional parameters to a request include things like query parameters, headers, port number, etc. All optional parameters have the type Option, which is a Monoid. This means that you can use mempty as the last argument of req to specify no optional parameters, or combine Options using mappend (or (<>)) to have several of them at once.

data Option scheme Source #

Opaque Option type is a Monoid you can use to pack collection of optional parameters like query parameters and headers. See sections below to learn which Option primitives are available.

Instances

Semigroup (Option scheme) Source # 

Methods

(<>) :: Option scheme -> Option scheme -> Option scheme #

sconcat :: NonEmpty (Option scheme) -> Option scheme #

stimes :: Integral b => b -> Option scheme -> Option scheme #

Monoid (Option scheme) Source # 

Methods

mempty :: Option scheme #

mappend :: Option scheme -> Option scheme -> Option scheme #

mconcat :: [Option scheme] -> Option scheme #

QueryParam (Option scheme) Source # 

Methods

queryParam :: ToHttpApiData a => Text -> Maybe a -> Option scheme Source #

Query parameters

This section describes a polymorphic interface that can be used to construct query parameters (of type Option) and form URL-encoded bodies (of type FormUrlEncodedParam).

(=:) :: (QueryParam param, ToHttpApiData a) => Text -> a -> param infix 7 Source #

This operator builds a query parameter that will be included in URL of your request after question sign ?. This is the same syntax you use with form URL encoded request bodies.

This operator is defined in terms of queryParam:

name =: value = queryParam name (pure value)

queryFlag :: QueryParam param => Text -> param Source #

Construct a flag, that is, valueless query parameter. For example, in the following URL a is a flag, b is a query parameter with a value:

https://httpbin.org/foo/bar?a&b=10

This operator is defined in terms of queryParam:

queryFlag name = queryParam name Nothing

class QueryParam param where Source #

A type class for query-parameter-like things. The reason to have overloaded queryParam is to be able to use it as an Option and as a FormUrlEncodedParam when constructing form URL encoded request bodies. Having the same syntax for these cases seems natural and user-friendly.

Minimal complete definition

queryParam

Methods

queryParam :: ToHttpApiData a => Text -> Maybe a -> param Source #

Create a query parameter with given name and value. If value is Nothing, it won't be included at all (i.e. you create a flag this way). It's recommended to use (=:) and queryFlag instead of this method, because they are easier to read.

Instances

QueryParam FormUrlEncodedParam Source # 

Methods

queryParam :: ToHttpApiData a => Text -> Maybe a -> FormUrlEncodedParam Source #

QueryParam (Option scheme) Source # 

Methods

queryParam :: ToHttpApiData a => Text -> Maybe a -> Option scheme Source #

Headers

header Source #

Arguments

:: ByteString

Header name

-> ByteString

Header value

-> Option scheme 

Create an Option that adds a header. Note that if you mappend two headers with the same names the leftmost header will win. This means, in particular, that you cannot create a request with several headers of the same name.

Cookies

Support for cookies is quite minimalistic at the moment, its' possible to specify which cookies to send using cookieJar and inspect Response to extract CookieJar from it (see responseCookieJar).

cookieJar :: CookieJar -> Option scheme Source #

Use the given CookieJar. A CookieJar can be obtained from a Response record.

Authentication

This section provides common authentication helpers in form of Options. You should always prefer the provided authentication Options to manual construction of headers because it ensures that you only use one authentication method at a time (they overwrite each other) and provides additional type safety that prevents leaking of credentials in cases when authentication relies on TLS for encrypting sensitive data.

basicAuth Source #

Arguments

:: ByteString

Username

-> ByteString

Password

-> Option Https

Auth Option

The Option adds basic authentication.

See also: https://en.wikipedia.org/wiki/Basic_access_authentication.

oAuth2Bearer Source #

Arguments

:: ByteString

Token

-> Option Https

Auth Option

The Option adds an OAuth2 bearer token. This is treated by many services as the equivalent of a username and password.

The Option is defined as:

oAuth2Bearer token = header "Authorization" ("Bearer " <> token)

See also: https://en.wikipedia.org/wiki/OAuth.

oAuth2Token Source #

Arguments

:: ByteString

Token

-> Option Https

Auth Option

The Option adds a not-quite-standard OAuth2 bearer token (that seems to be used only by GitHub). This will be treated by whatever services accept it as the equivalent of a username and password.

The Option is defined as:

oAuth2Token token = header "Authorization" ("token" <> token)

See also: https://developer.github.com/v3/oauth#3-use-the-access-token-to-access-the-api.

Other

port :: Int -> Option scheme Source #

Specify the port to connect to explicitly. Normally, Url you use determines default port, 80 for HTTP and 443 for HTTPS, this Option allows to choose arbitrary port overwriting the defaults.

decompress Source #

Arguments

:: (ByteString -> Bool)

Predicate that is given MIME type, it returns True when content should be decompressed on the fly.

-> Option scheme 

This Option controls whether gzipped data should be decompressed on the fly. By default everything except for application/x-tar is decompressed, i.e. we have:

decompress (/= "application/x-tar")

You can also choose to decompress everything like this:

decompress (const True)

responseTimeout Source #

Arguments

:: Int

Number of microseconds to wait

-> Option scheme 

Specify number of microseconds to wait for response. Default is 30 seconds.

httpVersion Source #

Arguments

:: Int

Major version number

-> Int

Minor version number

-> Option scheme 

HTTP version to send to server, default is HTTP 1.1.

Response

Response interpretations

ignoreResponse :: Proxy IgnoreResponse Source #

Use this as the fourth argument of req to specify that you want it to return the IgnoreResponse interpretation.

data JsonResponse a Source #

Make a request and interpret body of response as JSON. The handleHttpException method of MonadHttp instance corresponding to monad in which you use req will determine what to do in the case when parsing fails (JsonHttpException constructor will be used).

Instances

FromJSON a => HttpResponse (JsonResponse a) Source # 

Associated Types

type HttpResponseBody (JsonResponse a) :: * Source #

Methods

toVanillaResponse :: JsonResponse a -> Response (HttpResponseBody (JsonResponse a)) Source #

getHttpResponse :: Request -> Manager -> IO (JsonResponse a) Source #

type HttpResponseBody (JsonResponse a) Source # 

jsonResponse :: Proxy (JsonResponse a) Source #

Use this as the forth argument of req to specify that you want it to return the JsonResponse interpretation.

data BsResponse Source #

Make a request and interpret body of response as a strict ByteString.

bsResponse :: Proxy BsResponse Source #

Use this as the forth argument of req to specify that you want to interpret response body as a strict ByteString.

data LbsResponse Source #

Make a request and interpret body of response as a lazy ByteString.

lbsResponse :: Proxy LbsResponse Source #

Use this as the forth argument of req to specify that you want to interpret response body as a lazy ByteString.

data ReturnRequest Source #

This interpretation does not result in any call at all, but you can use the responseRequest function to extract Request that req has prepared. This is useful primarily for testing.

Note that when you use this interpretation inspecting response will diverge (i.e. it'll blow up with an error, don't do that).

returnRequest :: Proxy ReturnRequest Source #

Use this as the forth argument of req to specify that you want it to just return the request it consturcted without making any requests.

Inspecting a response

responseBody :: HttpResponse response => response -> HttpResponseBody response Source #

Get response body.

responseStatusCode :: HttpResponse response => response -> Int Source #

Get response status code.

responseStatusMessage :: HttpResponse response => response -> ByteString Source #

Get response status message.

responseHeader Source #

Arguments

:: HttpResponse response 
=> response

Response interpretation

-> ByteString

Header to lookup

-> Maybe ByteString

Header value if found

Look a particular header from a response.

responseCookieJar :: HttpResponse response => response -> CookieJar Source #

Get response CookieJar.

responseRequest :: ReturnRequest -> Request Source #

Get the original request from ReturnRequest response interpretation.

Defining your own interpretation

To create a new response interpretation you just need to make your data type an instance of HttpResponse type class.

class HttpResponse response where Source #

A type class for response interpretations. It allows to fully control how request is made and how its body is parsed.

Minimal complete definition

toVanillaResponse, getHttpResponse

Associated Types

type HttpResponseBody response :: * Source #

The associated type is type of body that can be extracted from a instance of HttpResponse.

Methods

toVanillaResponse :: response -> Response (HttpResponseBody response) Source #

The method describes how to get underlying Response record.

getHttpResponse :: Request -> Manager -> IO response Source #

This method describes how to make an HTTP request given Request (prepared by the rest of the library) and Manager.

Other

data HttpException Source #

Exceptions that this library throws.

Constructors

VanillaHttpException HttpException

A wrapper with an HttpException from Network.HTTP.Client

JsonHttpException String

A wrapper with Aeson-produced String describing why decoding failed

data CanHaveBody Source #

A simple Bool-like type we only have for better error messages. We use it as a kind and its data constructors as type-level tags.

See also: HttpMethod and HttpBody.

Constructors

CanHaveBody

Indeed can have a body

NoBody

Should not have a body

data Scheme Source #

A type-level tag that specifies URL scheme used (and thus if TLS is enabled). This is used to force TLS requirement for some authentication Options.

Constructors

Http

HTTP, no TLS

Https

HTTPS

Instances

Eq Scheme Source # 

Methods

(==) :: Scheme -> Scheme -> Bool #

(/=) :: Scheme -> Scheme -> Bool #

Data Scheme Source # 

Methods

gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Scheme -> c Scheme #

gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c Scheme #

toConstr :: Scheme -> Constr #

dataTypeOf :: Scheme -> DataType #

dataCast1 :: Typeable (* -> *) t => (forall d. Data d => c (t d)) -> Maybe (c Scheme) #

dataCast2 :: Typeable (* -> * -> *) t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c Scheme) #

gmapT :: (forall b. Data b => b -> b) -> Scheme -> Scheme #

gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Scheme -> r #

gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Scheme -> r #

gmapQ :: (forall d. Data d => d -> u) -> Scheme -> [u] #

gmapQi :: Int -> (forall d. Data d => d -> u) -> Scheme -> u #

gmapM :: Monad m => (forall d. Data d => d -> m d) -> Scheme -> m Scheme #

gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Scheme -> m Scheme #

gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Scheme -> m Scheme #

Ord Scheme Source # 
Show Scheme Source # 
Generic Scheme Source # 

Associated Types

type Rep Scheme :: * -> * #

Methods

from :: Scheme -> Rep Scheme x #

to :: Rep Scheme x -> Scheme #

type Rep Scheme Source # 
type Rep Scheme = D1 (MetaData "Scheme" "Network.HTTP.Req" "req-0.1.0-5YoxCmbCKF0ETpoqxvFlMW" False) ((:+:) (C1 (MetaCons "Http" PrefixI False) U1) (C1 (MetaCons "Https" PrefixI False) U1))