Clojure Noir Json Put

1.3k views Asked by At

I'm working through the tutorial Mark McGranaghan REST Tutorial however I'm trying to do it using Noir instead.

I can add new items, however it never takes the body of the PUT command.

I think the problem with how I'm trying to construct the put statement. I'm thinking the {:keys [id attrs]} is the issue, because I'm trying to tell it the json content is in the url, when its not, its in the body. Can anyone advise how i retrieve it from the body using noirs defpage?

(put is in a separate elem file)

(defn put [id attrs]
  (let [new-attrs (merge (get id) attrs)]
  (swap! elems assoc id new-attrs)
  new-attrs))

(defpage [:put "/elems/:id"] {:keys [id attrs]}
  (json-response (elem/put id attrs)))
3

There are 3 answers

0
Dax Fohl On

Use Chris Granger's JSON-parsing middleware function from here, and use it as described here to receive JSON data.

in your case it'll look like

(defpage [:put "/elems/:id"] {{:keys [attr1 attr2 attr3]} :backbone }
         "OK")

But you just need to add that "backbone" (I personally renamed it to "json-params") middleware first.

0
Rayne On

So these are form parameters? If so, destructuring params like you did here should work just fine. You can get the whole request inside the defpage using noir.request. I'd take at look at that and see what it contains. It should clarify things significantly.

0
mikebridge On

If you are passing "attrs=somevalue" in the post then that will work, but if you are trying to capture all the key-value pairs, this works for me in 1.3.0-beta1:

(defpage [:put "/elems/:id"] attrs 
  (response/json {:attrs attrs}))

then:

$ curl -H "Accept: application/json" -X PUT -d "foo=bar" http://localhost:8080/elems/123
=> {"attrs":{"id":"123","foo":"bar"}}