HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

Modulewreq-0.5.4.3Haskell98

Network.Wreq

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.

  • 13 types
  • 1 class
  • 78 values
  • Packagewreq-0.5.4.3
  • Exports92
  • LanguageHaskell98
  • LicenceBSD-3-Clause
  • SourceWreq.hs

HTTP verbs

0 declarations

Sessions

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.

GET

valueget :: String -> IO (Response ByteString)
#

Issue a GET request.

Example:

get "http://httpbin.org/get"
 
Example2 expressions
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"
 
Example3 expressions
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")

POST

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.

Example2 expressions
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.

Example2 expressions
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.

Example1 expression
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.

Example2 expressions
r <- post "http://httpbin.org/post" (toJSON [1,2,3])r ^? responseBody . key "json" . nth 0Just (Number 1.0)
valuepost :: Postable a => String -> a -> IO (Response ByteString)
#

Issue a POST request.

Example:

post "http://httpbin.org/post" (toJSON [1,2,3])
 
Example2 expressions
r <- post "http://httpbin.org/post" (toJSON [1,2,3])r ^? responseBody . key "json" . nth 2Just (Number 3.0)
valuepostWith :: Postable a => Options -> String -> a -> IO (Response ByteString)
#

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])
 
Example3 expressions
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")

HEAD

valuehead_ :: String -> IO (Response ())
#

Issue a HEAD request.

Example:

head_ "http://httpbin.org/get"
 
Example2 expressions
r <- head_ "http://httpbin.org/get"r ^? responseHeader "Content-Type"Just "application/json"
valueheadWith :: Options -> String -> IO (Response ())
#

Issue a HEAD request, using the supplied Options.

Example:

let opts = defaults & param "foo" .~ ["bar"]
headWith opts "http://httpbin.org/get"
 
Example3 expressions
let opts = defaults & param "foo" .~ ["bar"]r <- headWith opts "http://httpbin.org/get"r ^? responseHeader "Connection"Just "keep-alive"

OPTIONS

PUT

PATCH

DELETE

valuedelete :: String -> IO (Response ByteString)
#

Issue a DELETE request.

Example:

delete "http://httpbin.org/delete"
 
Example2 expressions
r <- delete "http://httpbin.org/delete"r ^. responseStatus . statusCode200

Custom Method

Custom Payload Method

Incremental consumption of responses

0 declarations

GET

Configuration

11 declarations
datadata Options
#

Options for configuring a client.

Instances1Show
  • Show OptionsDefined in wreq-0.5.4.3 · Network.Wreq.Internal.Types

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"
 
valueparam :: Text -> Lens' Options [Text]
#

A lens onto all query parameters with the given name (there can legitimately be zero or more).

In this example, we construct the query URL "http://httpbin.org/get?foo=bar&foo=quux".

let opts = defaults Control.Lens.& param "foo" Control.Lens..~ ["bar", "quux"]
getWith opts "http://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"
 
valueheaders :: Lens' Options [Header]
#

A lens onto all headers (there can legitimately be zero or more).

In this example, we print all the headers sent by default with every request.

print (defaults Control.Lens.^. headers)
 

Authentication

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.

datadata Auth
#

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.

Instances2Eq, Show
  • Eq AuthDefined in wreq-0.5.4.3 · Network.Wreq.Internal.Types
  • Show AuthDefined in wreq-0.5.4.3 · Network.Wreq.Internal.Types
valueauth :: Lens' Options (Maybe Auth)
#

A lens onto request authentication.

Example (note the use of TLS):

let opts = defaults Control.Lens.& Lens.auth Control.Lens.?~ basicAuth "user" "pass"
getWith opts "https://httpbin.org/basic-auth/user/pass"
 
valuebasicAuth
  1. :: ByteString

    Username.

  2. -> ByteString

    Password.

  3. -> Auth
#

Basic 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.

Example3 expressions
let opts = defaults & auth ?~ basicAuth "user" "pass"r <- getWith opts "https://httpbin.org/basic-auth/user/pass"r ^? responseBody . key "authenticated"Just (Bool True)
valueoauth2Token :: ByteString -> Auth
#

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"
 

Proxy settings

datadata Proxy
#

Define a HTTP proxy, consisting of a hostname and port number.

Constructors

Instances4Eq, Ord, Read, Show
  • Eq ProxyDefined in http-client-0.7.19 · Network.HTTP.Client.Types
  • Ord ProxyDefined in http-client-0.7.19 · Network.HTTP.Client.Types
  • Read ProxyDefined in http-client-0.7.19 · Network.HTTP.Client.Types
  • Show ProxyDefined in http-client-0.7.19 · Network.HTTP.Client.Types

Using a manager with defaults

Payloads for POST and PUT

1 declaration

URL-encoded form data

datadata FormParam where
#

A key/value pair for an application/x-www-form-urlencoded POST request body.

Constructors

Instances7Show, Postable, Patchable, Putable, …
classclass FormValue a where
#

A 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.

Instances21FormValue, …

Multipart form data

typetype Part = PartM IO
#
Instances6Postable, Patchable, Putable
  • Postable PartDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphan
  • Patchable PartDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphan
  • Putable PartDefined in wreq-0.5.4.3 · Network.Wreq.Types · orphan
  • Postable [Part]Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphan
  • Patchable [Part]Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphan
  • Putable [Part]Defined in wreq-0.5.4.3 · Network.Wreq.Types · orphan

Smart constructors

valuepartText
  1. :: Text

    Name of the corresponding <input>.

  2. -> Text

    The body for this Part.

  3. -> Part
#

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.

valuepartString
  1. :: Text

    Name of the corresponding <input>.

  2. -> String

    The body for this Part.

  3. -> Part
#

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.

valuepartFile
  1. :: Text

    Name of the corresponding <input>.

  2. -> FilePath

    The name of the local file to upload.

  3. -> Part
#

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.

valuepartFileSource
  1. :: Text

    Name of the corresponding <input>.

  2. -> FilePath

    The name of the local file to upload.

  3. -> Part
#

Stream a Part from a file.

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.

Responses

15 declarations
datadata Response body
#

A simple representation of the HTTP response.

Since 0.1.0

Instances4Functor, Foldable, Traversable, Show
valueresponseHeader
  1. :: HeaderName

    Header name to match.

  2. -> Traversal' (Response body) ByteString
#

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")
 
datadata Status
#

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.

Instances8Bounded, Enum, Eq, Data, Ord, Show, …
datadata HistoriedResponse body
#

A datatype holding information on redirected requests and the final response.

Since 0.4.1

Instances6Functor, Foldable, Traversable, Show, Generic, Rep

Link headers

Decoding responses

valueasJSON
  1. :: (MonadThrow m, FromJSON a)
  2. => Response ByteString
  3. -> m (Response a)
#

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")
 

Cookies

6 declarations

These are only the most frequently-used cookie-related lenses. See Network.Wreq.Lens for the full accounting of them all.

datadata Cookie
#
Instances2Read, Show
  • Read CookieDefined in http-client-0.7.19 · Network.HTTP.Client.Types
  • Show CookieDefined in http-client-0.7.19 · Network.HTTP.Client.Types

Parsing responses

2 declarations
valueatto :: Parser a -> Fold ByteString a
#

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.

Example8 expressions
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"]