From Hask Till Dawn

Rethinking webservice and APIs in Haskell: servant 0.2

Earlier this year, I announced the first version of servant. The goal was to speed up webservice development by getting rid of as much boilerplate as possible. It definitely was an improvement but not quite enough. Assisted this time with Sönke Hahn (of Nikki and the Robots fame) and Julian Arni, two of my now ex-coworkers, we completely rewrote everything and came up with a new way to describe webservices APIs in Haskell. This post introduces servant 0.2, which now lives in its own github org.

Webservice APIs as types

The meat of the new servant is the fact that we now describe webservice APIs as types. And we write these types by combining “API combinators”, that each have a precise meaning. We use type-level string literals for static fragments of an endpoint.

Endpoints are separated from one another with :<|>, similar to Alternative’s <|> separating alternative parsers. URL Captures, GET parameters, request bodies and headers are strongly typed and only made available to server handlers by explicit mentions in the type for the corresponding endpoint. They automatically become arguments to the handler functions.

Here’s our previous example expanded to make use of these few features.

This combinator-based approach lets us define server-side behavior and data-dependency with types, letting the library handle all the GET parameter/capture/request body extraction and letting you worry only about what you need to do with these values. But that doesn’t stop there. servant can also generate Haskell and Javascript functions to query servant webservices and API docs.

Want to read more about this?

We have a Getting Started slideshow that walks you through the basics of the library.

We have haddocks for the 4 packages that are full of examples and explanations.