Haskell Language Servant


Example

Servant is a library for declaring APIs at the type-level and then:

  • write servers (this part of servant can be considered a web framework),
  • obtain client functions (in haskell),
  • generate client functions for other programming languages,
  • generate documentation for your web applications
  • and more...

Servant has a concise yet powerful API. A simple API can be written in very few lines of code:

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}

import Data.Text
import Data.Aeson.Types
import GHC.Generics
import Servant.API

data SortBy = Age | Name

data User = User {
  name :: String,
  age :: Int
} deriving (Eq, Show, Generic)

instance ToJSON User  -- automatically convert User to JSON

Now we can declare our API:

type UserAPI = "users" :> QueryParam "sortby" SortBy :> Get '[JSON] [User]

which states that we wish to expose /users to GET requests with a query param sortby of type SortBy and return JSON of type User in the response.

Now we can define our handler:

-- This is where we'd return our user data, or e.g. do a database lookup
server :: Server UserAPI
server = return [User "Alex" 31]

userAPI :: Proxy UserAPI
userAPI = Proxy

app1 :: Application
app1 = serve userAPI server

And the main method which listens on port 8081 and serves our user API:

main :: IO ()
main = run 8081 app1

Note, Stack has a template for generating basic APIs in Servant, which is useful for getting up and running very quick.