如何使用Happstack创建JSON Rest API?JSON正文



我正在尝试使用Happstack创建一个JSON REST api。它应该允许带有JSON主体的POSTS。我该怎么做?happstack的API中的所有函数似乎都是根据参数名称查找的。它认为正文总是url编码的。

如果Happstack无法实现,我应该使用哪个框架?

好吧,这是我想出来的。

{-# 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. 

相关内容

  • 没有找到相关文章

最新更新