Search code examples
jsonpostclojurecompojure

Accessing POST json in clojure


EDIT - The source code is on github if you're interested. Thanks


I am a bit confused as to how to access json data that has been posted to a url in clojure; I just can't seem to get it to work.

This is my route:

(cc/POST "/add" 
request
(str ": " request))

I am not entirely sure what I have to put in place of request - I just saw some blog online and tried to follow it, but couldn't get it to work.

Here's how I'm trying to post: (from fiddler)

fiddler posting data

note: request header port is different in the image; it's a mistake, I was trying to mess with that data to see what it says so ignore that part in the above image please

In curl, I'm just doing this:

curl -X POST -H "Content-Type: application/json" -d '{"foo":"bar","baz":5}' 
     http://localhost:3005/add

It looks like clojure is not receiving the json data that I posted at all.

Here's what the request var contains:

: {:scheme :http, :query-params {}, :form-params {}, :request-method :post, 
   :query-string nil, :route-params {}, :content-type "\"application/json\"", 
   :uri "/event", :server-name "localhost", :params {}, 
   :headers {"user-agent" "Fiddler", "content-type" "\"application/json\"", 
          "content-length" "23", "host" "localhost:3005"}, 
   :content-length 23, :server-port 3005, :character-encoding nil, :body #}

As you can see, all params are empty...

I am using compojure and cheshire - and I can convert data into json and return them just fine for GET routes.. I need to figure out how to pass json and convert it into clojure data..

thanks


Solution

  • That's because :params is filled by a ring middleware which deals with "form-encoded" body.

    You can use ring-json to wrap your application into this other middleware. It will parse the JSON body and fill :params accordingly. (https://github.com/ring-clojure/ring-json)