How to combine Servant and React Admin, Part 1 : the Servant API type
This article is the first part of a series of medior level Haskell posts, focused on a very common problem: how to quickly set up a REST API and a minimal web UI. This is the short version, for the full version you can click here .
We will show how you can accomplish this easily using:
- an expressive REST server library
- the React-Admin UI library
The REST server will be written by using the Servant library, which offers an extremely ergonomic way of declaring an API and then filling out a server out a server, as well as generating a client.
In this first post we will look at the Haskell Servant API type, the full definition will look like this at first :
type WebApi = "comments" :> Get '[ JSON] [Comment]
The API here is very declarative. We express that we want to retrieve a list of comments, in JSON format, by sending a GET request to the comments REST resource. Comment is a Haskell record defined like this :
data Comment =
Comment
{ content :: String
}
deriving (Generic, Show)
instance ToJSON Comment
instance FromJSON Comment
We need to make sure we can turn Comment into a JSON record, hence the FromJSON instance.
What we now have is just a declaration of the API, we still need to implement the server. The implementation is rather simple, because there is only one REST resource of course :
listComments :: Handler [String] listComments = return ["A comment", "Another comment"] server :: Server WebApi server = listComments
The Handler monad here just provides us with a way to perform IO and indicate failure, if any.
Servant is not a web server, so we also need a web server to run our web application. Servant itself only defines the web application. We will run the web app by using WAI
This is a short synthesis of the full post, which can be found on the blogs section of Propellant here. In it we go a lot deeper into all the parts of the API and end with a running server that can be queried through curl. Follow up posts will explore how to interact through a React-Admin webapp.