On Jul 19, 9:26 pm, Moritz Angermann <
moritz.angerm...@gmail.com>
wrote:
> I wanted to write some RESTful service with Compojure and ended up
> sending JSON straight to Compojure. The problem is, as it has been
> with Werkzeug (Python WSGI Framework), that the framework did not
> expose the raw request.
Actually, it does :)
You can access the raw body of the request with (request :body). This
will return an InputStream instance that can then be read from. Here's
an example:
(use 'compojure)
(use 'clojure.contrib.duck-streams)
(use 'clojure.contrib.json.read)
(defroutes site
(POST "/raw"
(prn (slurp* (request :body))))
(POST "/json"
(prn (read-json (slurp* (request :body))))))
Note that if the content-type of the request is set to "application/x-
www-form-urlencoded", then these routes will fail, because Compojure
will first try to parse the JSON as a urlencoded form, and 'use up'
the InputStream. I mention this because a lot of HTTP client libraries
assume you're sending a urlencoded form when you're doing a POST.
You'd need to explicitly set the content-type to "application/json"
for it to work.
Alternatively, you could use the routes* function:
(def site
(routes*
(POST "/raw"
(prn (slurp* (request :body))))
(POST "/json"
(prn (read-json (slurp* (request :body)))))))
This function will not add the middleware used to parse urlencoded
forms, so it'll ignore the content-type and won't touch the body's
InputStream. However, it's probably a better idea to just get the
content-type correct :)
- James