A Haskell Microservice

James Carlson
2 min readFeb 18, 2021

--

The other day I needed a little server app that would receive data as an HTTP request and save it on disk in a specified directory. Each data record consisted of a file path and the the file contents in the form

{ fileName: String, contents: String }

The request was to be a POST request with url http://localhost:8077/save. There was to be one other endpoint, GET http://localhost:8077/hello. The server would respond with “Yes, I am here.” Useful for checking on whether the server was alive. Let’s name this app filingService.

I had written two other Haskell microservices before, e.g, pdfServer, which receives LaTeX files via POST request, saves the file to disk, converts it to PDF, and replies with a link to the PDF file. Again, a single-purpose program.

It was a simple matter to reshape the code of pdfServer to make filingService. The reshaping consisted mostly of deleting code, an activity that I’ve come to greatly enjoy. Starting with 171 lines of code in three files, I ended up with 58 lines in two files, Main.hs and Document.hs. Here is the code for the principle function of module Main:

main = scotty 8077 $ do
middleware corsPolicy
middleware logStdoutDev
get "/hello" $ do
html $ mconcat ["Yes, I am still here\n"]
post "/save" $ do
document <- jsonData :: ActionM Document
liftIO $ Document.write document
middleware $ staticPolicy (noDots >-> addBase "filingService")

Short, to the point, with a clear statement of the program’s intention. The other module, Document, defines the type of a document and sets forth what one can do with one, namely convert to and from JSON or write it to a file. Just 20 lines of code here, excluding import statements.

Simplicity and Clarity

What I like best about such programs is their simplicity and clarity. Very short, they do just one thing, and one can easily see how the code relates to the problem solved. The code for filingService, which is on GitHub, uses the Scotty library. Not as sophisticated as Servant, but simpler to use (IMHO) and more than adequate for the task at hand.

Note

I’ve used both filingService and pdfServer to support Elm apps that I’ve been working on. One of these is minilatex.lamdera.app, illustrated in the figure below. It is for creating, editing, and distributing LaTeX docs on the web. Real time rendering! Give it a try and let me know if it works for you.

--

--