17 APIs using Servant

 

This chapter covers

  • Providing typesafe APIs, using Servant
  • Implementing a WAI application
  • Automatically deriving clients for the API

In the last chapter, we discussed how to implement the conversion of Haskell data to and from JSON and how to store that data in a database. We also provided a few types for the todo list API we want to use.

In this chapter, we will complete the project by first exploring the Servant ecosystem of libraries and packages to define a typesafe API and define a server for it. After doing so, we extend the server to also serve HTML to the client. We then wrap things up by automatically deriving a client application for the API server.

17.1 Defining a typesafe API

For our server, we will write an HTTP/JSON API, meaning we will use HTTP as our protocol and JSON as the data serialization format. JSON is something we have already taken care of, so now it’s time to worry about the network. While there are many ways of talking to the network, we don’t want to work on a low level but, rather, focus on the definition of the API instead of worrying about pesky network details. A large list of libraries and packages exist to help us work with the network, but we will focus on a well-known, industry-hardened library that is known for its type safety: Servant.

17.1.1 Typed APIs with Servant

17.1.2 Phantom types

17.1.3 Implementing the API

17.2 Running the application

17.2.1 The WAI application

17.2.2 Application middleware

17.2.3 Producing HTML from data

17.3 Deriving a client

17.3.1 Using servant-client

17.3.2 Defining commands for the CLI

17.3.3 Implementing the client

Summary