dakrone / clj-http

An idiomatic clojure http client wrapping the apache client. Officially supported version.
http://clojars.org/clj-http
MIT License
1.78k stars 408 forks source link

json output coercion fails on exceptional HTTP codes #552

Closed Happy-Monad closed 4 years ago

Happy-Monad commented 4 years ago

I'm using json output coercion with Chesire in conjunction with the :throw-exceptions false option. When the response is returned with a 2XX status code the body contents are being parsed, however upon exceptional status codes (404, 500) the response body is kept as a string. This is happening both with client/get, client/post and client/request functions.

I share below the dependencies, code and sample test server

Dependencies

[clj-http "3.10.1"] [cheshire "5.10.0"]

Code

(require '[clj-http.client :as client])
(:body (client/get "http://127.0.0.1/200" {:as :json :throw-exceptions false}))  ;; {:foo "bar"}
(:body (client/get "http://127.0.0.1/500" {:as :json :throw-exceptions false}))  ;; "{\n  \"foo\": \"bar\"\n}\n"

Test server (Python3.7)

from flask import Flask, jsonify
app = Flask(__name__)

@app.route("/200", methods=['GET', 'POST'])
def http_200():
    return jsonify({"foo":"bar"}), 200

@app.route("/500", methods=['GET', 'POST'])
def http_500():
    return jsonify({"foo":"bar"}), 500

if __name__ == '__main__':
    app.run('127.0.0.1', port=80, debug=True)
rymndhng commented 4 years ago

Hi @Happy-Monad, use the add the option :coerce :always to get the behavior you want.

See https://github.com/dakrone/clj-http#output-coercion for more information

Happy-Monad commented 4 years ago

Thanks for that, I completely missed that line of the readme. I'll close the thread.