Clojure: JSON request with http.async.client library


Lately I was writing Clojure code that needed to do the POST request to the external service. Additional requirement was that this request should use JSON as a format of a data in the body. I was using http.async.client library for doing my network communication. Because I couldn’t find any example of such request I’ve spent some time before I was done. To help you, I will post my solution.

The typical POST request looks so:

(with-open [client (http/create-client)]
  (let [resp (http/POST client "http://url" :body "SampleBody")]
    ;; do something with resp
    ))

when we want to use JSON as a content type we need to add header info about it (as addition we specify UTF-8 as character set for this JSON):

:headers {:Content-Type "application/json; charset=UTF-8" }

Second we need to convert our data in body to JSON format (which is the whole “tricky”). We can easily do it with clojure/data.json:

:body (json/write-str {:key1 "keyValue1"
                       :key2 "keyValue2"
                       :key3 "keyValue3"})

so the full code looks like this:

(with-open [client (http/create-client)]
           (let [response (http/POST client "http://url"
                                   :headers
                                   {:Content-Type "application/json; charset=UTF-8"}
                                   :body
                                   (json/write-str {:key1 "keyValue1"
								                    :key2 "keyValue2"
													:key3 "keyValue3"}))]
;; do something with response
))

Quite simple, but it’s not so obvious at first.

Note: remember to add clojure/data.json to your project dependencies


You may also like

Lesser known Clojure: variants of threading macro

ClojureScript: JavaScript Interop

Template method pattern