Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create JSON Rest API with Happstack? JSON body?

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?

like image 821
Sean Clark Hess Avatar asked Jan 14 '12 22:01

Sean Clark Hess


1 Answers

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. 
like image 200
Sean Clark Hess Avatar answered Oct 16 '22 06:10

Sean Clark Hess