Question

I'm trying to create a JSON REST api using Happstack. It should allow POSTS with a JSON body. How can I do this? All the functions in happstack's API seem to look things up based on parameter name. It thinks the body is always url-encoded.

If it isn't possible with Happstack, which framework should I use?

Was it helpful?

Solution

Alright, here's what I figured out.

{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-}
import qualified Data.ByteString.Lazy.Char8 as L
import Happstack.Server
import Happstack.Server.Types
import Control.Monad.IO.Class (liftIO)

import Data.Data (Data, Typeable)

-- easiest to serialize/deserialize objects
data Unit = Unit { x :: Int, y :: Int } deriving (Show, Eq, Data, Typeable)

-- put this function in a library somewhere
getBody :: ServerPart L.ByteString
getBody = do
    req  <- askRq 
    body <- liftIO $ takeRequestBody req 
    case body of 
        Just rqbody -> return . unBody $ rqbody 
        Nothing     -> return "" 

myRoute :: ServerPart Response
myRoute = do
    body <- getBody -- it's a ByteString
    let unit = fromJust $ A.decode body :: Unit -- how to parse json
    ok $ toResponse $ A.encode unit -- how to send json back. 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top