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

16. Ring II, the Two Routes

Published 01 September 16

In this second installment of our beginner friendly introduction to Ring the API goes from being read-only to being read-write. You also learn about juxt, slurp, and how to parse an incoming request body.

Show notes

<– 001 –>

In the previous episode we started building an API for an address book application using Ring. This is what the code looks like so far. We use an atom containing a map as our database of contacts. The Ring handler so far only handles GET requests to the root path. We’re using the Ring Jetty adapter to talk to the outside world.

(ns rolodex.core
  (:require [ring.adapter.jetty :refer [run-jetty]]))

(defn random-uuid []
  (java.util.UUID/randomUUID))

(def contacts (atom (let [id (random-uuid)]
                      {id {:id id
                           :full-name "Trish Turtle"
                           :skills ["LISP" "Lambda Calculus"]}})))

(defn handler "request -> response"
  [req]
  (if (and (= (:request-method req) :get) (= (:uri req) "/"))
    {:status 200
     :headers {"Content-Type" "application/edn; charset=UTF-8"}
     :body (prn-str (vals @contacts))}))

(defonce server
  (run-jetty #'handler {:port 3000
                        :join? false}))

<– 002 –>

Looking at project.clj you can I see I’ve kept the dependencies to a minimum. There’s just Clojure itself and then the Ring Jetty adapter. In real a world project you should pull in some libraries containing middleware and routing functionality, and we’ll cover some of those later in the series, but first I want you to grok the concepts of Ring, it will help a lot once you start combining these third party pieces.

(defproject rolodex "0.1.0"
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [ring/ring-jetty-adapter "1.5.0"]])

If you want to follow along, which you should, then grab the Rolodex repository from GitHub. Just do a git clone, then cd into it, and then checkout ring-part-1 branch. This is the code we ended up with at the end of the previous episode.

browse source code

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

rolodex-gui

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/.