bpereira
bpereira

Reputation: 1016

Ring and Compojure - POST Requests with content-type application/json does not work

What's the correct way to send a POST request with content-type application/json?

When I send the request to my application, I can't retrive the parameters.

curl -X POST http://localhost:3000/agents --data '{"name":"verma"}' --header "Content-type:application/json"

I'm using:

[org.clojure/clojure "1.8.0"]
[compojure "1.5.1"]
[ring/ring-defaults "0.2.1"]]

And my handler.cljs is:

▾|    1 (ns sof.rest.handler
 |    2   (:require [compojure.core :refer :all]
 |    3             [compojure.route :as route]
 |    4             [clojure.data.json :as json]
 |    8             [ring.middleware.defaults :refer [wrap-defaults api-defaults]]))
 |    9
 |   10 (defn json-response [data & [status]]
 |   11   {:status (or status 200)
 |   12    :headers {"Content-Type" "application/json"}
 |   13    :body (json/write-str data)})
 |   14
 |   15 (defroutes app-routes
 |~  16   (POST "/agents" params (println params))
 |   21
~|   22 (def app
~|   23   (wrap-defaults app-routes api-defaults))

Those are the params logged when I run the CURL command:

{:ssl-client-cert nil, :remote-addr 0:0:0:0:0:0:0:1, :params {}, :route- 
params {}, :headers {accept */*, user-agent curl/7.54.0, content-type 
application/json, content-length 16, host localhost:3000}, :server-port 
3000, :content-length 16, :form-params {}, :compojure/route [:post 
/agents], :query-params {}, :content-type application/json, :character- 
encoding nil, :uri /agents, :server-name localhost, :query-string nil, 
:body #object[org.eclipse.jetty.server.HttpInput 0x70504fbe 
org.eclipse.jetty.server.HttpInput@70504fbe], :scheme :http, :request- 
method :post}

Upvotes: 3

Views: 2347

Answers (1)

Taylor Wood
Taylor Wood

Reputation: 16194

You can slurp the :body input stream (read it into a string) and parse its JSON. Something like this:

(POST "/agents" request
  (let [body (json/read-str (slurp (:body request)))]
    (println body)))

But you should use the Ring middleware to do this automatically.

Upvotes: 3

Related Questions