This episode is for subscribers only. Sign Up or Log in to watch it.

17. Ring III, Return of the Middleware

Published 09 September 16

We add GET, PUT, DELETE operations to the contact book API. In the process we pull out the EDN handling into its own middleware, and come across some handy Regex tips. This third episode picks up the pace a bit, but by now that shouldn’t be a problem.

Show notes

This episode builds upon episodes 13 and 16 about Ring, although you can watch it by itself if you’re already familiar with the basics of Ring request and response maps.

All code is on Github, in the lambdaisland/rolodex repository. The starting point for this episode is the ring-part-2 branch, the final code can be found in ring-part-3.

There’s a supporting Reagent app that you can use to test the API. You can find instructions in the show notes.

Let’s have another look at the code we have so far. It consists of an atom containing our contact database, and two functions corresponding with the two API operations we already support. Then there’s the handler which takes care of the routing, and finally the invocation to start Jetty.

The assumption that we’re using EDN is encoded in five different places. It determines which Content-Type header to set, how to parse the request, and how to encode the response.

What if we want to switch to JSON or Transit later on? What if we want to support multiple formats through content negotiation? As it stands that will be much harder than it needs to be. Let’s clean this up.

Instead of repeating the content-type in every response, we can just set it once in the handler.

browse source code

At the start of this episode, the code is as found in the ring-part-2 branch. The end result is in the ring-part-3 branch.


To test out and play around with the API there’s a web app that you can also grab from github. Make sure your API is running at port 3000, and then start the app by issuing

lein run

and surfing to http://localhost:3449.

To get around cross-origin restrictions in browsers the server part of this app will proxy requests to /api to http://localhost:3000/.