resthttphaskellhttp-headersservant

How can I get access to http headers in Servant?


I have a simple servant application with rest api:

type API = "items" :> Get '[JSON] [MyData]

app :: Application
app = serve api server

api :: Proxy API
api = Proxy

server :: Server API
server = getItems

getItems :: ExceptT ServantErr IO [MyData]
getItems = ......

startApp :: IO ()
startApp = run 1234 app

How can I get access to http headers and return a certain response, say, http403, depending on a condition?


Solution

  • Using Servant's Header (Servant Docs)

    type API = "items" 
               :> Header "Auth-token" Text 
               :> Get '[JSON] [MyData]
    

    then

    handler :: Maybe Text -> ExceptT ServantErr IO [MyData]
    handler (Just "secret-code") = right [mydata]
    handler _                    = left $ err403 { errBody = "no access" }