- Assumptions
- Benefits
- The Recipe—Code
- Testing the Solution
- Notes on the Recipe
- Conclusion
Notes on the Recipe
The Compojure library is designed to make RESTful URIs easy to work with. Note in particular the project.clj file:
[ring/ring-defaults "0.1.5"]] :plugins [[lein-ring "0.9.5"]] :ring {:handler rest-demo.handler/app}
Notice the ring-defaults library. We’ll use this when we examine parameters passed in. Also note the lein-ring plug-in. This enables us to start the app from the command line. It will also enable us to modify the app when it is running and to see the results without restarting the server.
Also note the :ring {:handler... syntax. This points to the part of the application that will handle the incoming requests.
Now look at the file handler.clj, in particular the namespace:
(ns rest-demo.handler (:require [compojure.core :refer :all] [compojure.route :as route] [ring.middleware.defaults :refer [wrap-defaults site-defaults]]))
Note that we load the Compojure libraries for handling routes, and we use the ring.middleware for parameter handling.
Now observe the handle-http function definition:
(defn handle-http [] (context "/:id" [id] (defroutes api-routes (GET "/" [] (str "get called: " id "\n")) (POST "/" {form-params :form-params} (str "post called: " id "\n" form-params " \n")) (PUT "/" req (str "put called with params: " req)) (DELETE "/" [] (str "delete called: " id "\n")))))
This function handles the parameters for the particular http request type. Here we just do simple handlers for the different http request types. This handles requests in the format:
http://servername/2
Now note the following function:
(defroutes app-routes (handle-http) (route/not-found (str "This is the default page - try " "<a href='http://localhost:4000/33'>this</a>\n")))
This is the main route-handler function. It delegates most of its responsibilities to our handle-http function above. If that returns nil, then it displays a "Not Found" response.
Now note the following symbol:
(def app (wrap-defaults app-routes (assoc-in site-defaults [:security :anti-forgery] false)))
This is the application hook. We point to this in the project.clj file. It takes the route definitions in app-routes and feeds that into the function result of wrap-defaults. The wrap-defaults function adds middleware to the route to enable URI parameter input. We switch off the anti-forgery middleware so our simple curl tests will work. You shouldn’t do this in your production application.