http-conduit

Most of Yesod is about serving content over HTTP. But that’s only half the story: someone has to receive it. And even when you’re writing a web app, sometimes that someone will be you. If you want to consume content from other services or interact with RESTful APIs, you’ll need to write client code. And the recommended approach for that is http-conduit.

This chapter is not directly connected to Yesod, and will be generally useful for anyone wanting to make HTTP requests.

Synopsis

  1. {-# LANGUAGE OverloadedStrings #-}
  2. import Network.HTTP.Conduit -- the main module
  3. -- The streaming interface uses conduits
  4. import Data.Conduit
  5. import Data.Conduit.Binary (sinkFile)
  6. import qualified Data.ByteString.Lazy as L
  7. import Control.Monad.IO.Class (liftIO)
  8. main :: IO ()
  9. main = do
  10. -- Simplest query: just download the information from the given URL as a
  11. -- lazy ByteString.
  12. simpleHttp "http://www.example.com/foo.txt" >>= L.writeFile "foo.txt"
  13. -- Use the streaming interface instead. We need to run all of this inside a
  14. -- ResourceT, to ensure that all our connections get properly cleaned up in
  15. -- the case of an exception.
  16. runResourceT $ do
  17. -- We need a Manager, which keeps track of open connections. simpleHttp
  18. -- creates a new manager on each run (i.e., it never reuses
  19. -- connections).
  20. manager <- liftIO $ newManager def
  21. -- A more efficient version of the simpleHttp query above. First we
  22. -- parse the URL to a request.
  23. req <- liftIO $ parseUrl "http://www.example.com/foo.txt"
  24. -- Now get the response
  25. res <- http req manager
  26. -- And finally stream the value to a file
  27. responseBody res $$+- sinkFile "foo.txt"
  28. -- Make it a POST request, don't follow redirects, and accept any
  29. -- status code.
  30. let req2 = req
  31. { method = "POST"
  32. , redirectCount = 0
  33. , checkStatus = \_ _ _ -> Nothing
  34. }
  35. res2 <- http req2 manager
  36. responseBody res2 $$+- sinkFile "post-foo.txt"

Concepts

The simplest way to make a request in http-conduit is with the simpleHttp function. This function takes a String giving a URL and returns a ByteString with the contents of that URL. But under the surface, there are a few more steps:

  • A new connection Manager is allocated.

  • The URL is parsed to a Request. If the URL is invalid, then an exception is thrown.

  • The HTTP request is made, following any redirects from the server.

  • If the response has a status code outside the 200-range, an exception is thrown.

  • The response body is read into memory and returned.

  • runResourceT is called, which will free up any resources (e.g., the open socket to the server).

If you want more control of what’s going on, then you can configure any of the steps above (plus a few more) by explicitly creating a Request value, allocating your Manager manually, and using the http and httpLbs functions.

Request

The easiest way to creating a Request is with the parseUrl function. This function will return a value in any Failure monad, such as Maybe or IO. The last of those is the most commonly used, and results in a runtime exception whenever an invalid URL is provided. However, you can use a different monad if, for example, you want to validate user input.

  1. import Network.HTTP.Conduit
  2. import System.Environment (getArgs)
  3. import qualified Data.ByteString.Lazy as L
  4. import Control.Monad.IO.Class (liftIO)
  5. main :: IO ()
  6. main = do
  7. args <- getArgs
  8. case args of
  9. [urlString] ->
  10. case parseUrl urlString of
  11. Nothing -> putStrLn "Sorry, invalid URL"
  12. Just req -> withManager $ \manager -> do
  13. res <- httpLbs req manager
  14. liftIO $ L.putStr $ responseBody res
  15. _ -> putStrLn "Sorry, please provide exactly one URL"

The Request type is abstract so that http-conduit can add new settings in the future without breaking the API (see the Settings Type chapter for more information). In order to make changes to individual records, you use record notation. For example, a modification to our program that issues HEAD requests and prints the response headers would be:

  1. {-# LANGUAGE OverloadedStrings #-}
  2. import Network.HTTP.Conduit
  3. import System.Environment (getArgs)
  4. import qualified Data.ByteString.Lazy as L
  5. import Control.Monad.IO.Class (liftIO)
  6. main :: IO ()
  7. main = do
  8. args <- getArgs
  9. case args of
  10. [urlString] ->
  11. case parseUrl urlString of
  12. Nothing -> putStrLn "Sorry, invalid URL"
  13. Just req -> withManager $ \manager -> do
  14. let reqHead = req { method = "HEAD" }
  15. res <- http reqHead manager
  16. liftIO $ do
  17. print $ responseStatus res
  18. mapM_ print $ responseHeaders res
  19. _ -> putStrLn "Sorry, please provide example one URL"

There are a number of different configuration settings in the API, some noteworthy ones are:

proxy

Allows you to pass the request through the given proxy server.

redirectCount

Indicate how many redirects to follow. Default is 10.

checkStatus

Check the status code of the return value. By default, gives an exception for any non-2XX response.

requestBody

The request body to be sent. Be sure to also update the method. For the common case of url-encoded data, you can use the urlEncodedBody function.

Manager

The connection manager allows you to reuse connections. When making multiple queries to a single server (e.g., accessing Amazon S3), this can be critical for creating efficient code. A manager will keep track of multiple connections to a given server (taking into account port and SSL as well), automatically reaping unused connections as needed. When you make a request, http-conduit first tries to check out an existing connection. When you’re finished with the connection (if the server allows keep-alive), the connection is returned to the manager. If anything goes wrong, the connection is closed.

To keep our code exception-safe, we use the ResourceT monad transformer. All this means for you is that your code needs to be wrapped inside a call to runResourceT, either implicitly or explicitly, and that code inside that block will need to liftIO to perform normal IO actions.

There are two ways you can get ahold of a manager. newManager will return a manager that will not be automatically closed (you can use closeManager to do so manually), while withManager will start a new ResourceT block, allow you to use the manager, and then automatically close the ResourceT when you’re done. If you want to use a ResourceT for an entire application, and have no need to close it, you should probably use newManager.

One other thing to point out: you obviously don’t want to create a new manager for each and every request; that would defeat the whole purpose. You should create your Manager early and then share it.

Response

The Response datatype has three pieces of information: the status code, the response headers, and the response body. The first two are straight-forward; let’s discuss the body.

The Response type has a type variable to allow the response body to be of multiple types. If you want to use http-conduit‘s streaming interface, you want this to be a Source. For the simple interface, it will be a lazy ByteString. One thing to note is that, even though we use a lazy ByteString, the entire response is held in memory. In other words, we perform no lazy I/O in this package.

The conduit package does provide a lazy module which would allow you to read this value in lazily, but like any lazy I/O, it’s a bit unsafe, and definitely non-deterministic. If you need it though, you can use it.

http and httpLbs

So let’s tie it together. The http function gives you access to the streaming interface (i.e., it returns a Response using a BufferedSource) while httpLbs returns a lazy ByteString. Both of these return values in the ResourceT transformer so that they can access the Manager and have connections handled properly in the case of exceptions.

If you want to ignore the remainder of a large response body, you can connect to the sinkNull sink. The underlying connection will automatically be closed, preventing you from having to read a large response body over the network.