Skip to content

Instantly share code, notes, and snippets.

@philjackson
Last active July 27, 2023 13:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philjackson/d7ea949c76982a618a1c002568f7b182 to your computer and use it in GitHub Desktop.
Save philjackson/d7ea949c76982a618a1c002568f7b182 to your computer and use it in GitHub Desktop.
Sensible compojure/ring defaults for an API
(ns my-api.handler
(:require [compojure.core :refer :all]
[ring.util.response :refer [response status content-type]]
[ring.middleware.params :refer [wrap-params]]
[ring.middleware.keyword-params :refer [wrap-keyword-params]]
[ring.middleware.json :refer [wrap-json-response wrap-json-body]]))
(defroutes app-routes
(context "/v1" []
(GET "/" req
(response {:hello ["world" "universe"]})))
(ANY "*" req
(-> (response {:error "Not found."
:status 404})
(status 404))))
(def app
(-> app-routes
;; make entries in :params keywords
wrap-keyword-params
;; parse the query string and put the results into :params on
;; request
wrap-params
;; parses the body and converts it to a clojure structure
;; in :body on request
(wrap-json-body {:keywords? true :bigdecimals? true})
;; sets the content-type header to json and will convert the
;; response itself to json
wrap-json-response))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment