Test if Flask response is JSON

As of Flask 1.0, response.get_json() will parse the response data as JSON or raise an error.

response = c.get("https://stackoverflow.com/")
assert response.get_json()["message"] == "hello world"

jsonify sets the content type to application/json. Additionally, you can try parsing the response data as JSON. If it fails to parse, your test will fail.

from flask import json
assert response.content_type == 'application/json'
data = json.loads(response.get_data(as_text=True))
assert data['message'] == 'hello world'

Typically, this test on its own doesn’t make sense. You know it’s JSON since jsonify returned without error, and jsonify is already tested by Flask. If it was not valid JSON, you would have received an error while serializing the data.

Leave a Comment