JSON Web Service

Let’s create a very simple web service: it takes a JSON request and returns a JSON response. We’re going to write the server in WAI/Warp, and the client in http-conduit. We’ll be using aeson for JSON parsing and rendering. We could also write the server in Yesod itself, but for such a simple example, the extra features of Yesod don’t add much.

Server

WAI uses the conduit package to handle streaming request bodies, and efficiently generates responses using blaze-builder. aeson uses attoparsec for parsing; by using attoparsec-conduit we get easy interoperability with WAI. This plays out as:

  1. {-# LANGUAGE OverloadedStrings #-}
  2. import Network.Wai (Response, responseLBS, Application, requestBody)
  3. import Network.HTTP.Types (status200, status400)
  4. import Network.Wai.Handler.Warp (run)
  5. import Data.Aeson.Parser (json)
  6. import Data.Conduit.Attoparsec (sinkParser)
  7. import Control.Monad.IO.Class (liftIO)
  8. import Data.Aeson (Value, encode, object, (.=))
  9. import Control.Exception (SomeException)
  10. import Data.ByteString (ByteString)
  11. import Data.Conduit (ResourceT, ($$))
  12. import Control.Exception.Lifted (handle)
  13. main :: IO ()
  14. main = run 3000 app
  15. app :: Application
  16. app req = handle invalidJson $ do
  17. value <- requestBody req $$ sinkParser json
  18. newValue <- liftIO $ modValue value
  19. return $ responseLBS
  20. status200
  21. [("Content-Type", "application/json")]
  22. $ encode newValue
  23. invalidJson :: SomeException -> ResourceT IO Response
  24. invalidJson ex = return $ responseLBS
  25. status400
  26. [("Content-Type", "application/json")]
  27. $ encode $ object
  28. [ ("message" .= show ex)
  29. ]
  30. -- Application-specific logic would go here.
  31. modValue :: Value -> IO Value
  32. modValue = return

Client

http-conduit was written as a companion to WAI. It too uses conduit and blaze-builder pervasively, meaning we once again get easy interop with aeson. A few extra comments for those not familiar with http-conduit:

  • A Manager is present to keep track of open connections, so that multiple requests to the same server use the same connection. You usually want to use the withManager function to create and clean up this Manager, since it is exception safe.

  • We need to know the size of our request body, which can’t be determined directly from a Builder. Instead, we convert the Builder into a lazy ByteString and take the size from there.

  • There are a number of different functions for initiating a request. We use http, which allows us to directly access the data stream. There are other higher level functions (such as httpLbs) that let you ignore the issues of sources and get the entire body directly.

  1. {-# LANGUAGE OverloadedStrings #-}
  2. import Network.HTTP.Conduit
  3. ( http, parseUrl, withManager, RequestBody (RequestBodyLBS)
  4. , requestBody, method, Response (..)
  5. )
  6. import Data.Aeson (Value (Object, String))
  7. import Data.Aeson.Parser (json)
  8. import Data.Conduit (($$))
  9. import Data.Conduit.Attoparsec (sinkParser)
  10. import Control.Monad.IO.Class (liftIO)
  11. import Data.Aeson (encode, (.=), object)
  12. main :: IO ()
  13. main = withManager $ \manager -> do
  14. value <- liftIO makeValue
  15. -- We need to know the size of the request body, so we convert to a
  16. -- ByteString
  17. let valueBS = encode value
  18. req' <- liftIO $ parseUrl "http://localhost:3000/"
  19. let req = req' { method = "POST", requestBody = RequestBodyLBS valueBS }
  20. Response status version headers body <- http req manager
  21. resValue <- body $$ sinkParser json
  22. liftIO $ handleResponse resValue
  23. -- Application-specific function to make the request value
  24. makeValue :: IO Value
  25. makeValue = return $ object
  26. [ ("foo" .= ("bar" :: String))
  27. ]
  28. -- Application-specific function to handle the response from the server
  29. handleResponse :: Value -> IO ()
  30. handleResponse = print