Skip to content

Instantly share code, notes, and snippets.

@qwtel
Last active August 26, 2016 08:29
Show Gist options
  • Save qwtel/98bc6d1dc3a0b8b86a1cd2a5187cd616 to your computer and use it in GitHub Desktop.
Save qwtel/98bc6d1dc3a0b8b86a1cd2a5187cd616 to your computer and use it in GitHub Desktop.
Ring REST JSON and namespaced clojure.spec

Handy for a ring REST server that is spec'd via the upcomming clojure.spec library in Clojure 1.9, since it encourages the use of namespaced keywords.

A request like

POST /endpoint Content-Type: application/json {"name": "Test", "id": -1}

will be parsed as

{:my.spec/name "Test"
 :my.spec/id -1}

while a response like

{:my.spec/name "Test"
 :my.spec/id   "5f711778-1fdd-455e-aa4c-ca015a9774a"
 :my.spec/more "Values"}

will be sent over the wire like

{
  "name": "Test",
  "id": "5f711778-1fdd-455e-aa4c-ca015a9774a",
  "more": "Values
}
(require '[ring.middleware.json :refer [wrap-json-body wrap-json-response]])
(def app
(-> app-routes
(wrap-json-body {:keywords? #(keyword "my.spec" %)})
(wrap-json-response {:key-fn name})))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment