Issue a GET request.
Example:
get "http://httpbin.org/get"
r <- get "http://httpbin.org/get"r ^. responseStatus . statusCode200
:: a typeCtrl KGHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05
Modulewreq-0.5.4.3Haskell98
A library for client-side HTTP requests, focused on ease of use.
When reading the examples in this module, you should assume the following environment:
-- Make it easy to write literal ByteString and Text values.
{-# LANGUAGE OverloadedStrings #-}
-- Our handy module.
import Network.Wreq
-- Operators such as (&) and (.~).
import Control.Lens
-- Conversion of Haskell values to JSON.
import Data.Aeson (Data.Aeson.toJSON)
-- Easy traversal of JSON data.
import Data.Aeson.Lens (key, nth)
There exist some less frequently used lenses that are not exported from this module; these can be found in Network.Wreq.Lens.
The basic HTTP functions (get, post, and so on) in this module have a few key drawbacks:
If several requests go to the same server, there is no reuse of TCP connections.
There is no management of cookies across multiple requests.
This makes these functions inefficient and verbose for many common uses. For greater efficiency, use the Network.Wreq.Session module.
Issue a GET request.
Example:
get "http://httpbin.org/get"
r <- get "http://httpbin.org/get"r ^. responseStatus . statusCode200
Issue a GET request, using the supplied Options.
Example:
let opts = defaults & param "foo" .~ ["bar"]
getWith opts "http://httpbin.org/get"
let opts = defaults & param "foo" .~ ["bar"]r <- getWith opts "http://httpbin.org/get"r ^? responseBody . key "url"Just (String "http://httpbin.org/get?foo=bar")
The Postable class determines which Haskell types can be used as POST payloads.
Part and [Part] give a request body with a
Content-Type of multipart/form-data. Constructor functions
include partText and partFile.
r <- post "http://httpbin.org/post" (partText "hello" "world")r ^? responseBody . key "form" . key "hello"Just (String "world")
(ByteString, ByteString) and FormParam (and lists of
each) give a request body with a Content-Type of
application/x-www-form-urlencoded. The easiest way to use this is
via the (:=) constructor.
r <- post "http://httpbin.org/post" ["num" := 31337, "str" := "foo"]r ^? responseBody . key "form" . key "num"Just (String "31337")
The "magical" type conversion on the right-hand side of := above is due to the FormValue class. This package provides sensible instances for the standard string and number types. You may need to explicitly add types to the values (e.g. :: String) in order to evade ambigous type errors.
r <- post "http://httpbin.org/post" ["num" := (31337 :: Int), "str" := ("foo" :: String)]The Value type gives a JSON request body with a
Content-Type of application/json. Any instance of
ToJSON can of course be converted to a Value using
toJSON.
r <- post "http://httpbin.org/post" (toJSON [1,2,3])r ^? responseBody . key "json" . nth 0Just (Number 1.0)
Issue a POST request, using the supplied Options.
Example:
let opts = defaults & param "foo" .~ ["bar"]
postWith opts "http://httpbin.org/post" (toJSON [1,2,3])
let opts = defaults & param "foo" .~ ["bar"]r <- postWith opts "http://httpbin.org/post" (toJSON [1,2,3])r ^? responseBody . key "url"Just (String "http://httpbin.org/post?foo=bar")
Issue a HEAD request.
Example:
head_ "http://httpbin.org/get"
r <- head_ "http://httpbin.org/get"r ^? responseHeader "Content-Type"Just "application/json"
Issue a PUT request.
Issue a PUT request, using the supplied Options.
Issue a PATCH request.
Issue a PATCH request, using the supplied Options.
Issue a DELETE request.
Example:
delete "http://httpbin.org/delete"
r <- delete "http://httpbin.org/delete"r ^. responseStatus . statusCode200
Issue a custom-method request
Example:
customMethod "PATCH" "http://httpbin.org/patch"
r <- customMethod "PATCH" "http://httpbin.org/patch"r ^. responseStatus . statusCode200
Issue a custom request method request, using the supplied Options.
Example:
let opts = defaults & redirects .~ 0
customMethodWith "PATCH" opts "http://httpbin.org/patch"
let opts = defaults & redirects .~ 0r <- customMethodWith "PATCH" opts "http://httpbin.org/patch"r ^. responseStatus . statusCode200
Issue a custom request method. Keep track of redirects and return the HistoriedResponse
Example:
customHistoriedMethod "GET" "http://httpbin.org/redirect/3"
r <- customHistoriedMethod "GET" "http://httpbin.org/redirect/3"length (r ^. hrRedirects)3
Issue a custom request method request, using the supplied Options. Keep track of redirects and return the HistoriedResponse.
Issue a custom-method request with a payload
Issue a custom-method request with a payload, using the supplied Options.
Issue a custom-method historied request with a payload
Issue a custom-method historied request with a paylod, using the supplied Options.
Options for configuring a client.
A lens onto configuration of the connection manager provided by the http-client package.
In this example, we enable the use of OpenSSL for (hopefully) secure connections:
import OpenSSL.Session (context)
import Network.HTTP.Client.OpenSSL
let opts = defaults Control.Lens.& manager Control.Lens..~ Left (Network.HTTP.Client.OpenSSL.opensslManagerSettings context)
Network.HTTP.Client.OpenSSL.withOpenSSL $
getWith opts "https://httpbin.org/get"
In this example, we also set the response timeout to 10000 microseconds:
import OpenSSL.Session (context)
import Network.HTTP.Client.OpenSSL
import Network.HTTP.Client (defaultManagerSettings, managerResponseTimeout)
let opts = defaults Control.Lens.& manager Control.Lens..~ Left (Network.HTTP.Client.OpenSSL.opensslManagerSettings context)
Control.Lens.& manager Control.Lens..~ Left (defaultManagerSettings { managerResponseTimeout = responseTimeoutMicro 10000 } )
Network.HTTP.Client.OpenSSL.withOpenSSL $
getWith opts "https://httpbin.org/get"
A lens onto the maximum number of redirects that will be followed before an exception is thrown.
In this example, a HttpException will be thrown with a TooManyRedirects constructor, because the maximum number of redirects allowed will be exceeded.
let opts = defaults Control.Lens.& redirects Control.Lens..~ 3
getWith opts "http://httpbin.org/redirect/5"
A lens onto all query parameters.
A traversal onto the cookie with the given name, if one exists.
N.B. This is an "illegal" Traversal': we can change the cookieName of the associated Cookie so that it differs from the name provided to this function.
A lens onto all cookies.
A lens to get the optional status check function
Do not use HTTP authentication unless you are using TLS encryption. These authentication tokens can easily be captured and reused by an attacker if transmitted in the clear.
Supported authentication types.
Do not use HTTP authentication unless you are using TLS encryption. These authentication tokens can easily be captured and reused by an attacker if transmitted in the clear.
AWSv4AWS request signing version 4
Eq AWSAuthVersionDefined in wreq-0.5.4.3 · Network.Wreq.Internal.TypesShow AWSAuthVersionDefined in wreq-0.5.4.3 · Network.Wreq.Internal.TypesBasic authentication. This consists of a plain username and password.
Example (note the use of TLS):
let opts = defaults & auth ?~ basicAuth "user" "pass"
getWith opts "https://httpbin.org/basic-auth/user/pass"
Note here the use of the Control.Lens.?~ setter to turn an Auth
into a Maybe Auth, to make the type of the RHS compatible with
the auth lens.
let opts = defaults & auth ?~ basicAuth "user" "pass"r <- getWith opts "https://httpbin.org/basic-auth/user/pass"r ^? responseBody . key "authenticated"Just (Bool True)
oauth1Auth :: ByteStringConsumer token
-> ByteStringConsumer secret
-> ByteStringOAuth token
-> ByteStringOAuth token secret
-> AuthOAuth1 authentication. This consists of a consumer token, a consumer secret, a token and a token secret
An OAuth2 bearer token. This is treated by many services as the equivalent of a username and password.
Example (note the use of TLS):
let opts = defaults & auth ?~ oauth2Bearer "1234abcd"
getWith opts "https://public-api.wordpress.com/rest/v1/me/"
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.
Example (note the use of TLS):
let opts = defaults & auth ?~ oauth2Token "abcd1234"
getWith opts "https://api.github.com/user"
awsSessionTokenAuth :: AWSAuthVersionSignature version (V4)
-> ByteStringAWS AccessKeyId
-> ByteStringAWS SecretAccessKey
-> ByteStringAWS STS SessionToken
-> AuthDefine a HTTP proxy, consisting of a hostname and port number.
ProxyproxyHost :: ByteStringThe host name of the HTTP proxy in URI format. IPv6 addresses in square brackets.
proxyPort :: IntThe port number of the HTTP proxy.
A lens onto proxy configuration.
Example:
let opts = defaults Control.Lens.& proxy Control.Lens.?~ httpProxy "localhost" 8000
getWith opts "http://httpbin.org/get"
Note here the use of the Control.Lens.?~ setter to turn a Proxy
into a Maybe Proxy, to make the type of the RHS compatible with
the proxy lens.
A product type for representing more complex payload types.
Raw :: ContentType -> RequestBody -> PayloadA key/value pair for an application/x-www-form-urlencoded
POST request body.
(:=) :: FormValue v => ByteString -> v -> FormParaminfixr 3Show FormParamDefined in wreq-0.5.4.3 · Network.Wreq.Internal.TypesPostable FormParamDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanPatchable FormParamDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanPutable FormParamDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanPostable [FormParam]Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanPatchable [FormParam]Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanPutable [FormParam]Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanA type that can be rendered as the value portion of a key/value
pair for use in an application/x-www-form-urlencoded POST
body. Intended for use with the FormParam type.
The instances for String, strict Text, and lazy Text are all encoded using UTF-8 before being URL-encoded.
The instance for Maybe gives an empty string on Nothing, and otherwise uses the contained type's instance.
FormValue ByteStringDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue ByteStringDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue IntegerDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue StringDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue Int16Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue Int32Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue Int64Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue Int8Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue Word16Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue Word32Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue Word64Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue Word8Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue DoubleDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue FloatDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue IntDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue WordDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue TextDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue BuilderDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue TextDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue ()Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanFormValue a => FormValue (Maybe a)Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanPostable PartDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanPatchable PartDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanPutable PartDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphanPostable [Part]Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanPatchable [Part]Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanPutable [Part]Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphanA lens onto the name of the input element associated with
part of a multipart form upload.
A lens onto the filename associated with part of a multipart form upload.
A lens onto the content-type associated with part of a multipart form upload.
A lens onto the code that fetches the data associated with part of a multipart form upload.
partBS :: Applicative m=> TextName of the corresponding <input>.
-> ByteStringThe body for this Part.
-> PartM mMake a Part whose content is a strict ByteString.
The Part does not have a file name or content type associated with it.
partLBS :: Applicative m=> TextName of the corresponding <input>.
-> ByteStringThe body for this Part.
-> PartM mMake a Part whose content is a lazy ByteString.
The Part does not have a file name or content type associated with it.
Make a Part whose content is a strict Text, encoded as
UTF-8.
The Part does not have a file name or content type associated
with it.
Make a Part whose content is a String, encoded as UTF-8.
The Part does not have a file name or content type associated
with it.
partFile Make a Part from a file.
The entire file will reside in memory at once. If you want constant memory usage, use partFileSource.
The FilePath supplied will be used as the file name of the Part. If you do not want to reveal this name to the server, you must remove it prior to uploading.
The Part does not have a content type associated with it.
partFileSource A simple representation of the HTTP response.
Since 0.1.0
Functor ResponseDefined in http-client-0.7.19 · Network.HTTP.Client.TypesFoldable ResponseDefined in http-client-0.7.19 · Network.HTTP.Client.TypesTraversable ResponseDefined in http-client-0.7.19 · Network.HTTP.Client.TypesShow body => Show (Response body)Defined in http-client-0.7.19 · Network.HTTP.Client.TypesA lens onto the body of a response.
r <- get "http://httpbin.org/get"
print (r Control.Lens.^. responseBody)
A lens onto all matching named headers in an HTTP response.
To access exactly one header (the result will be the empty string if
there is no match), use the (Control.Lens.^.) operator.
r <- get "http://httpbin.org/get"
print (r Control.Lens.^. responseHeader "Content-Type")
To access at most one header (the result will be Nothing if there
is no match), use the (Control.Lens.^?) operator.
r <- get "http://httpbin.org/get"
print (r Control.Lens.^? responseHeader "Content-Transfer-Encoding")
To access all (zero or more) matching headers, use the
(Control.Lens.^..) operator.
r <- get "http://httpbin.org/get"
print (r Control.Lens.^.. responseHeader "Set-Cookie")
responseLink :: ByteStringParameter name to match.
-> ByteStringParameter value to match.
-> Fold (Response body) LinkA fold over Link headers, matching on both parameter name
and value.
For example, here is a Link header returned by the GitHub search API.
Link:
<https://api.github.com/search/code?q=addClass+user%3Amozilla&page=2>; rel="next",
<https://api.github.com/search/code?q=addClass+user%3Amozilla&page=34>; rel="last"And here is an example of how we can retrieve the URL for the next link
programatically.
r <- get "https://api.github.com/search/code?q=addClass+user:mozilla"
print (r Control.Lens.^? responseLink "rel" "next" . linkURL)
A fold over any cookies that match the given name.
r <- get "http://www.nytimes.com/"
print (r Control.Lens.^? responseCookie "RMID")
A lens onto all headers in an HTTP response.
A lens onto all cookies set in the response.
A lens onto the status of an HTTP response.
HTTP Status.
Only the statusCode is used for comparisons.
Please use mkStatus to create status codes from code and message, or the Enum instance or the status code constants (like ok200). There might be additional record members in the future.
Note that the Show instance is only for debugging.
Bounded StatusDefined in http-types-0.12.4 · Network.HTTP.Types.StatusEnum StatusDefined in http-types-0.12.4 · Network.HTTP.Types.StatusBe advised, that when using the "enumFrom*" family of methods or ranges in lists, it will generate all possible status codes.
E.g. [status100 .. status200] generates Statuses of 100, 101, 102 .. 198, 199, 200
The statuses not included in this library will have an empty message.
Eq StatusDefined in http-types-0.12.4 · Network.HTTP.Types.StatusData StatusDefined in http-types-0.12.4 · Network.HTTP.Types.StatusOrd StatusDefined in http-types-0.12.4 · Network.HTTP.Types.StatusStatuses are ordered according to their status codes only.
Show StatusDefined in http-types-0.12.4 · Network.HTTP.Types.StatusGeneric StatusDefined in http-types-0.12.4 · Network.HTTP.Types.Statustype Rep Status = D1 ('MetaData "Status"
"Network.HTTP.Types.Status"
"http-types-0.12.4-KkMxTblWZY5WJ4M2x8W7s"
'False) (C1 ('MetaCons "Status"
'PrefixI 'True) (S1 ('MetaSel ('Just "statusCode"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Int) :*: S1 ('MetaSel ('Just "statusMessage"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 ByteString)))Defined in http-types-0.12.4 · Network.HTTP.Types.StatusA lens onto the numeric identifier of an HTTP status.
A lens onto the textual description of an HTTP status.
A datatype holding information on redirected requests and the final response.
Since 0.4.1
Functor HistoriedResponseDefined in http-client-0.7.19 · Network.HTTP.ClientFoldable HistoriedResponseDefined in http-client-0.7.19 · Network.HTTP.ClientTraversable HistoriedResponseDefined in http-client-0.7.19 · Network.HTTP.ClientShow body => Show (HistoriedResponse body)Defined in http-client-0.7.19 · Network.HTTP.ClientGeneric (HistoriedResponse body)Defined in http-client-0.7.19 · Network.HTTP.Clienttype Rep (HistoriedResponse body) = D1 ('MetaData "HistoriedResponse"
"Network.HTTP.Client"
"http-client-0.7.19-HrfOahD9xgrKGFtDZYGgUO"
'False) (C1 ('MetaCons "HistoriedResponse"
'PrefixI 'True) (S1 ('MetaSel ('Just "hrRedirects"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 [(Request, Response ByteString)]) :*: (S1 ('MetaSel ('Just "hrFinalRequest"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Request) :*: S1 ('MetaSel ('Just "hrFinalResponse"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Response body)))))Defined in http-client-0.7.19 · Network.HTTP.ClientA lens onto the final request of a historied response.
A lens onto the final response of a historied response.
A lens onto the list of redirects of a historied response.
An element of a Link header.
A lens onto the URL portion of a Link element.
A lens onto the parameters of a Link element.
Convert the body of an HTTP response from JSON to a suitable Haskell type.
In this example, we use asJSON in the IO monad, where it will
throw a JSONError exception if conversion to the desired type
fails.
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics (Generic)
{- This Haskell type corresponds to the structure of a
response body from httpbin.org. -}
data GetBody = GetBody {
headers :: Data.Map.Map Text Text
, args :: Data.Map.Map Text Text
, origin :: Text
, url :: Text
} deriving (Show, Generic)
-- Get GHC to derive a FromJSON instance for us.
instance FromJSON GetBody
{- The fact that we want a GetBody below will be inferred by our
use of the "headers" accessor function. -}
foo = do
r <- asJSON =<< get "http://httpbin.org/get"
print (headers (r Control.Lens.^. responseBody))
If we use asJSON in the Either monad, it will return Left
with a JSONError payload if conversion fails, and Right with a
Response whose responseBody is the converted value on success.
Convert the body of an HTTP response from JSON to a Value.
In this example, we use asValue in the IO monad, where it will
throw a JSONError exception if the conversion to Value fails.
foo = do
r <- asValue =<< get "http://httpbin.org/get"
print (r Control.Lens.^? responseBody . key "headers" . key "User-Agent")
These are only the most frequently-used cookie-related lenses. See Network.Wreq.Lens for the full accounting of them all.
A lens onto the name of a cookie.
A lens onto the value of a cookie.
A lens onto the expiry time of a cookie.
A lens onto the domain of a cookie.
A lens onto the path of a cookie.
Turn an attoparsec Parser into a Fold.
Both headers and bodies can contain complicated data that we may need to parse.
Example: when responding to an OPTIONS request, a server may return the list of verbs it supports in any order, up to and including changing the order on every request (which httpbin.org /actually does/!). To deal with this possibility, we parse the list, then sort it.
import Data.Attoparsec.ByteString.Char8 as Aimport Data.List (sort)let comma = skipSpace >> "," >> skipSpacelet verbs = A.takeWhile isAlpha_ascii `sepBy` commar <- options "http://httpbin.org/get"r ^. responseHeader "Allow" . atto verbs . to sort["GET","HEAD","OPTIONS"]
The same as atto, but ensures that the parser consumes the entire input.
Equivalent to:
atto_ myParser = atto (myParser <* endOfInput)