Charlie Harvey

Servant: REST APIs as types

In recent months, have been slowly working my way through Brian P. Hogan’s 57 Exercises for Programmers in Haskell in my lunch breaks and on bus journeys. You can see the github repo if you’re interested.

Servant logo

As I work my way through the exercises, I have been trying to use idiomatic Haskell ways of doing things — a great way to become familiar with some of the libraries that are out there.

Tools like stack, hspec and QuickCheck have made building and testing feel really pleasant.

Libraries like wreq and aeson have been able to do a lot of heavy lifting for me. As Larry Wall famously said in the Camel Book the three great virtues of a programmer [are]: laziness, impatience, and hubris. Libraries help with at least laziness and impatience!

The latest couple of exercises deal with creating and interacting with REST APIs, so I decided to have a play with Servant. A lot of people in the Haskell community have been very excited about Servant, so it was a good chance to see what all the fuss was about.

The Servant docs describe it as a Type-Level Web DSL. You describe your API using this DSL, effectively creating a type for it. Then, in the words of Taylor Fausak, With a single API description, you can implement a server, then get documentation and clients for free.

Creating the docs and clients is possible with virtually no boilerplate code and the compiler will help you out when you are making changes to your API. You can generate a client in Haskell or, if you prefer, in Angular, AXios, jQuery or vanilla JS.

And if that is not enough, you can also spit out a Swagger specification, allowing you to take advantage of all the power that Swagger provides.

In order to achieve this, some quite cool type and kind features need to be used including stuff like type-level strings, type-level lists, type-level operators, and type families. If you want to learn more about how those parts work, then Servant, Type Families, and Type-level Everything by Dennis Gosnell is a good place to start.

Finally, here is a very helpful video introducing Servant and going through some of the implementation by David Johnson.


Comments

  • Be respectful. You may want to read the comment guidelines before posting.
  • You can use Markdown syntax to format your comments. You can only use level 5 and 6 headings.
  • You can add class="your language" to code blocks to help highlight.js highlight them correctly.

Privacy note: This form will forward your IP address, user agent and referrer to the Akismet, StopForumSpam and Botscout spam filtering services. I don’t log these details. Those services will. I do log everything you type into the form. Full privacy statement.