Network.HTTP.Simple

http-conduit-2.2.3.1: HTTP client package with conduit interface and HTTPS support.

Safe Haskell | None
Language | Haskell98

Network.HTTP.Simple

Contents

- Perform requests
- Types
- Request constructions
- Request lenses
  - Basics
  - Request body
  - Special fields
- Response lenses
- Alternate spellings

Description

Simplified interface for common HTTP client interactions. Tutorial available at https://haskell-lang.org/library/http-client

Important note: `Request` is an instance of `IsString`, and therefore recommended usage is to turn on `OverloadedStrings`, e.g.

    {-# LANGUAGE OverloadedStrings #-}
    import Network.HTTP.Simple
    import qualified Data.ByteString.Lazy.Char8 as L8

    main :: IO ()
    main = httpLBS "http://example.com" >>= L8.putStrLn

Synopsis

- httpLBS :: MonadIO m => Request -> m (Response ByteString)
- httpNoBody :: MonadIO m => Request -> m (Response ())
- httpJSON :: (MonadIO m, FromJSON a) => Request -> m (Response a)
- httpJSONEither :: (MonadIO m, FromJSON a) => Request -> m (Response (Either JSONException a))
- httpSink :: (MonadIO m, MonadMask m) => Request -> (Response () -> Sink ByteString m a) -> m a
- httpSource :: (MonadResource m, MonadIO n) => Request -> (Response (ConduitM i ByteString n ()) -> ConduitM i o m r) -> ConduitM i o m r
- withResponse :: (MonadIO m, MonadMask m, MonadIO n) => Request -> (Response (ConduitM i ByteString n ()) -> m a) -> m a
- data Request :: *
- data Response body :: * -> *
- data JSONException
  - = JSONParseException Request (Response ()) ParseError
  - | JSONConversionException Request (Response Value) String
- data HttpException :: *
  - = HttpExceptionRequest Request HttpExceptionContent
  - | InvalidUrlException String String
- data Proxy :: * = Proxy {
  - proxyHost :: ByteString
  - proxyPort :: Int
  }
- defaultRequest :: Request
- parseRequest :: MonadThrow m => String -> m Request
- parseRequest_ :: String -> Request
- setRequestMethod :: ByteString -> Request -> Request
- setRequestSecure :: Bool -> Request -> Request
- setRequestHost :: ByteString -> Request -> Request
- setRequestPort :: Int -> Request -> Request
- setRequestPath :: ByteString -> Request -> Request
- addRequestHeader :: HeaderName -> ByteString -> Request -> Request
- getRequestHeader :: HeaderName -> Request -> [ByteString]
- setRequestHeader :: HeaderName -> [ByteString] -> Request -> Request
- setRequestHeaders :: [(HeaderName, ByteString)] -> Request -> Request
- setRequestQueryString :: [(ByteString, Maybe ByteString)] -> Request -> Request
- getRequestQueryString :: Request -> [(ByteString, Maybe ByteString)]
- setRequestBody :: RequestBody -> Request -> Request
- setRequestBodyJSON :: ToJSON a => a -> Request -> Request
- setRequestBodyLBS :: ByteString -> Request -> Request
- setRequestBodySource :: Int64 -> Source IO ByteString -> Request -> Request
- setRequestBodyFile :: FilePath -> Request -> Request
- setRequestBodyURLEncoded :: [(ByteString, ByteString)] -> Request -> Request
- setRequestIgnoreStatus :: Request -> Request
- setRequestBasicAuth :: ByteString -> ByteString -> Request -> Request
- setRequestManager :: Manager -> Request -> Request
- setRequestProxy :: Maybe Proxy -> Request -> Request
- getResponseStatus :: Response a -> Status
- getResponseStatusCode :: Response a -> Int
- getResponseHeader :: HeaderName -> Response a -> [ByteString]
- getResponseHeaders :: Response a -> [(HeaderName, ByteString)]
- getResponseBody :: Response a -> a
- httpLbs :: MonadIO m => Request -> m (Response ByteString)

# Perform requests

httpLBS :: MonadIO m => Request -> m (Response ByteString) #

Perform an HTTP request and return the body as a lazy `ByteString`. Note that the entire value will be read into memory at once (no lazy I/O will be performed).

Since: 2.1.10

httpNoBody :: MonadIO m => Request -> m (Response ()) #

Perform an HTTP request and ignore the response body.

Since: 2.2.2

httpJSON :: (MonadIO m, FromJSON a) => Request -> m (Response a) #

Perform an HTTP request and parse the body as JSON. In the event of an JSON parse errors, a `JSONException` runtime exception will be thrown.

Since: 2.1.10

httpJSONEither :: (MonadIO m, FromJSON a) => Request -> m (Response (Either JSONException a)) #

Perform an HTTP request and parse the body as JSON. In the event of an JSON parse errors, a `Left` value will be returned.

Since: 2.1.10

httpSink :: (MonadIO m, MonadMask m) => Request -> (Response () -> Sink ByteString m a) -> m a #

Perform an HTTP request and consume the body with the given `Sink`

Since: 2.1.10

httpSource :: (MonadResource m, MonadIO n) => Request -> (Response (ConduitM i ByteString n ()) -> ConduitM i o m r) -> ConduitM i o m r #

Perform an HTTP request, and get the response body as a Source.

The second argument to this function tells us how to make the Source from the Response itself. This allows you to perform actions with the status or headers, for example, in addition to the raw bytes themselves. If you just care about the response body, you can use `getResponseBody` as the second argument here.

    {-# LANGUAGE OverloadedStrings #-}
    import           Control.Monad.IO.Class       (liftIO)
    import           Control.Monad.Trans.Resource (runResourceT)
    import           Data.Conduit                 (($$))
    import qualified Data.Conduit.Binary          as CB
    import qualified Data.Conduit.List            as CL
    import           Network.HTTP.Simple
    import           System.IO                    (stdout)

    main :: IO ()
    main =
        runResourceT
            $ httpSource "http://httpbin.org/robots.txt" getSrc
           $$ CB.sinkHandle stdout
      where
        getSrc res = do
            liftIO $ print (getResponseStatus res, getResponseHeaders res)
            getResponseBody res

Since: 2.2.1

withResponse :: (MonadIO m, MonadMask m, MonadIO n) => Request -> (Response (ConduitM i ByteString n ()) -> m a) -> m a #

Perform an action with the given request. This employes the bracket pattern.

This is similar to `httpSource`, but does not require `MonadResource` and allows the result to not contain a `ConduitM` value.

Since: 2.2.3

# Types

data Request :: * #

All information on how to connect to a host and what should be sent in the HTTP request.

If you simply wish to download from a URL, see `parseRequest`.

The constructor for this data type is not exposed. Instead, you should use either the `defaultRequest` value, or `parseRequest` to construct from a URL, and then use the records below to make modifications. This approach allows http-client to add configuration options without breaking backwards compatibility.

For example, to construct a POST request, you could do something like:

    initReq <- parseRequest "http://www.example.com/path"
    let req = initReq
                { method = "POST"
                }

For more information, please see http://www.yesodweb.com/book/settings-types.

Since 0.1.0

Instances

Show Request |
Methods showsPrec :: Int -> Request -> ShowS # show :: Request -> String # showList :: [Request] -> ShowS #

data Response body :: * -> * #

A simple representation of the HTTP response.

Since 0.1.0

Instances

Functor Response |
Methods fmap :: (a -> b) -> Response a -> Response b # (<$) :: a -> Response b -> Response a #
Foldable Response |
Methods fold :: Monoid m => Response m -> m # foldMap :: Monoid m => (a -> m) -> Response a -> m # foldr :: (a -> b -> b) -> b -> Response a -> b # foldr' :: (a -> b -> b) -> b -> Response a -> b # foldl :: (b -> a -> b) -> b -> Response a -> b # foldl' :: (b -> a -> b) -> b -> Response a -> b # foldr1 :: (a -> a -> a) -> Response a -> a # foldl1 :: (a -> a -> a) -> Response a -> a # toList :: Response a -> [a] # null :: Response a -> Bool # length :: Response a -> Int # elem :: Eq a => a -> Response a -> Bool # maximum :: Ord a => Response a -> a # minimum :: Ord a => Response a -> a # sum :: Num a => Response a -> a # product :: Num a => Response a -> a #
Traversable Response |
Methods traverse :: Applicative f => (a -> f b) -> Response a -> f (Response b) # sequenceA :: Applicative f => Response (f a) -> f (Response a) # mapM :: Monad m => (a -> m b) -> Response a -> m (Response b) # sequence :: Monad m => Response (m a) -> m (Response a) #
Eq body => Eq (Response body) |
Methods (==) :: Response body -> Response body -> Bool # (/=) :: Response body -> Response body -> Bool #
Show body => Show (Response body) |
Methods showsPrec :: Int -> Response body -> ShowS # show :: Response body -> String # showList :: [Response body] -> ShowS #

data JSONException #

An exception that can occur when parsing JSON

Since: 2.1.10

Constructors

JSONParseException Request (Response ()) ParseError |
JSONConversionException Request (Response Value) String |

Instances

Show JSONException # |
Methods showsPrec :: Int -> JSONException -> ShowS # show :: JSONException -> String # showList :: [JSONException] -> ShowS #
Exception JSONException # |
Methods toException :: JSONException -> SomeException # fromException :: SomeException -> Maybe JSONException # displayException :: JSONException -> String #

data HttpException :: * #

An exception which may be generated by this library

Since: 0.5.0

Constructors

HttpExceptionRequest Request HttpExceptionContent | Most exceptions are specific to a `Request`. Inspect the `HttpExceptionContent` value for details on what occurred. Since: 0.5.0
InvalidUrlException String String | A URL (first field) is invalid for a given reason (second argument). Since: 0.5.0

Instances

Show HttpException |
Methods showsPrec :: Int -> HttpException -> ShowS # show :: HttpException -> String # showList :: [HttpException] -> ShowS #
Exception HttpException |
Methods toException :: HttpException -> SomeException # fromException :: SomeException -> Maybe HttpException # displayException :: HttpException -> String #

data Proxy :: * #

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

Constructors

Proxy |
Fields proxyHost :: ByteString The host name of the HTTP proxy. proxyPort :: Int The port number of the HTTP proxy.

Instances

Eq Proxy |
Methods (==) :: Proxy -> Proxy -> Bool # (/=) :: Proxy -> Proxy -> Bool #
Ord Proxy |
Methods compare :: Proxy -> Proxy -> Ordering # (<) :: Proxy -> Proxy -> Bool # (<=) :: Proxy -> Proxy -> Bool # (>) :: Proxy -> Proxy -> Bool # (>=) :: Proxy -> Proxy -> Bool # max :: Proxy -> Proxy -> Proxy # min :: Proxy -> Proxy -> Proxy #
Read Proxy |
Methods readsPrec :: Int -> ReadS Proxy # readList :: ReadS [Proxy] # readPrec :: ReadPrec Proxy # readListPrec :: ReadPrec [Proxy] #
Show Proxy |
Methods showsPrec :: Int -> Proxy -> ShowS # show :: Proxy -> String # showList :: [Proxy] -> ShowS #

# Request constructions

defaultRequest :: Request #

A default request value

Since: 0.4.30

parseRequest :: MonadThrow m => String -> m Request #

Convert a URL into a `Request`.

This defaults some of the values in `Request`, such as setting `method` to GET and `requestHeaders` to `[]`.

Since this function uses `MonadThrow`, the return monad can be anything that is an instance of `MonadThrow`, such as `IO` or `Maybe`.

You can place the request method at the beginning of the URL separated by a space, e.g.:

@@`parseRequeset "POST http://httpbin.org/post"` @@

Note that the request method must be provided as all capital letters.

`Request` created by this function won't cause exceptions on non-2XX response status codes.

Since: 0.4.30

parseRequest_ :: String -> Request #

Same as `parseRequest`, but in the cases of a parse error generates an impure exception. Mostly useful for static strings which are known to be correctly formatted.

# Request lenses

## Basics

setRequestMethod :: ByteString -> Request -> Request #

Set the request method

Since: 2.1.10

setRequestSecure :: Bool -> Request -> Request #

Set whether this is a secureHTTPS (`True`) or insecureHTTP (`False`) request

Since: 2.1.10

setRequestHost :: ByteString -> Request -> Request #

Set the destination host of the request

Since: 2.1.10

setRequestPort :: Int -> Request -> Request #

Set the destination port of the request

Since: 2.1.10

setRequestPath :: ByteString -> Request -> Request #

Lens for the requested path info of the request

Since: 2.1.10

addRequestHeader :: HeaderName -> ByteString -> Request -> Request #

Add a request header name/value combination

Since: 2.1.10

getRequestHeader :: HeaderName -> Request -> [ByteString] #

Get all request header values for the given name

Since: 2.1.10

setRequestHeader :: HeaderName -> [ByteString] -> Request -> Request #

Set the given request header to the given list of values. Removes any previously set header values with the same name.

Since: 2.1.10

setRequestHeaders :: [(HeaderName, ByteString)] -> Request -> Request #

Set the request headers, wiping out any previously set headers

Since: 2.1.10

setRequestQueryString :: [(ByteString, Maybe ByteString)] -> Request -> Request #

Set the query string parameters

Since: 2.1.10

getRequestQueryString :: Request -> [(ByteString, Maybe ByteString)] #

Get the query string parameters

Since: 2.1.10

## Request body

setRequestBody :: RequestBody -> Request -> Request #

Set the request body to the given `RequestBody`. You may want to consider using one of the convenience functions in the modules, e.g. `requestBodyJSON`.

Note: This will not modify the request method. For that, please use `requestMethod`. You likely don't want the default of `GET`.

Since: 2.1.10

setRequestBodyJSON :: ToJSON a => a -> Request -> Request #

Set the request body as a JSON value

Note: This will not modify the request method. For that, please use `requestMethod`. You likely don't want the default of `GET`.

This also sets the `content-type` to `application/json; chatset=utf8`

Since: 2.1.10

setRequestBodyLBS :: ByteString -> Request -> Request #

Set the request body as a lazy `ByteString`

Note: This will not modify the request method. For that, please use `requestMethod`. You likely don't want the default of `GET`.

Since: 2.1.10

setRequestBodySource #

Arguments

:: Int64 | length of source
-> Source IO ByteString |
-> Request |
-> Request |

Set the request body as a `Source`

Note: This will not modify the request method. For that, please use `requestMethod`. You likely don't want the default of `GET`.

Since: 2.1.10

setRequestBodyFile :: FilePath -> Request -> Request #

Set the request body as a file

Note: This will not modify the request method. For that, please use `requestMethod`. You likely don't want the default of `GET`.

Since: 2.1.10

setRequestBodyURLEncoded :: [(ByteString, ByteString)] -> Request -> Request #

Set the request body as URL encoded data

Note: This will not modify the request method. For that, please use `requestMethod`. You likely don't want the default of `GET`.

This also sets the `content-type` to `application/x-www-form-urlencoded`

Since: 2.1.10

## Special fields

setRequestIgnoreStatus :: Request -> Request #

Modify the request so that non-2XX status codes do not generate a runtime `StatusCodeException`.

Since: 0.4.29

setRequestBasicAuth #

Arguments

:: ByteString | username
-> ByteString | password
-> Request |
-> Request |

Set basic auth with the given username and password

Since: 2.1.10

setRequestManager :: Manager -> Request -> Request #

Instead of using the default global `Manager`, use the supplied `Manager`.

Since: 2.1.10

setRequestProxy :: Maybe Proxy -> Request -> Request #

Override the default proxy server settings

Since: 2.1.10

# Response lenses

getResponseStatus :: Response a -> Status #

Get the status of the response

Since: 2.1.10

getResponseStatusCode :: Response a -> Int #

Get the integral status code of the response

Since: 2.1.10

getResponseHeader :: HeaderName -> Response a -> [ByteString] #

Get all response header values with the given name

Since: 2.1.10

getResponseHeaders :: Response a -> [(HeaderName, ByteString)] #

Get all response headers

Since: 2.1.10

getResponseBody :: Response a -> a #

Get the response body

Since: 2.1.10

# Alternate spellings

httpLbs :: MonadIO m => Request -> m (Response ByteString) #

Alternate spelling of `httpLBS`

Since: 2.1.10