Building a Blog in Haskell with Yesod–Returning JSON

Posted on August 12, 2019 by Riccardo

This is a series about Yesod: a Haskell web framework that follows a similar philosophy to Rails. In fact, it is strongly opinionated and provides a lot of functionality out of the box.

A good read about Yesod is available online for free: Developing web applications with Haskell and Yesod. That’s why this series will be a commentary of the commits from a repo we will use to develop a super simple blog.

In other words, this won’t be good material to learn how to use Yesod. However, it will hopefully give an overview of how the framework works.

Series index:

Gimme JSON!

The plan for this post was to transform the entire blog into an API. Unfortunately, the compiler got in the middle. Therefore, this is just the first step towards that goal.

In particular, here we are going to see how to return the list of posts as JSON instead of as HTML.

Commit 53c06240c8b41438f35475284588e67950ff8800 is the initial attempt.

By adding json to the Post and User model, we get for free a ToJSON instance. Then, we can use it in the handler with

Notice that allPosts is a list of tuples. In particular, (post, user). That’s why the final JSON looks like the following:

Custom JSON

It’s cool to have the ToJSON instances generated for free. Unfortunately, that means we don’t have any control over the content of the JSON.

Commit 70e71484dd979fe43adf6295f4f6110e974a3214 fixes that by wrapping the (post, user) tuple into a new datatype with its own ToJSON instance:

That means our JSON now looks like this