6.2. JSON and Flask#
Flask doesn’t force you to use any one method for sending JSON back to the client. Below is an explanation of how to do it manually, which is followed by the recommended approach using jsonify.
6.2.1. Manual JSON Responses#
To correctly return JSON you should:
Serialise (convert) your Python data, usually a
dict, to a JSON‑encodedstr.Wrap that string in a
flask.Responseobject.Set the correct
Content‑Typeheader (application/json; charset=utf-8).(Optional) choose a status code and any extra headers.
For example:
@app.route("/api/test")
def api_test():
payload = {
"message": "Hello, this is some JSON!",
}
# 2. Serialise to a JSON string
json_str = json.dumps(payload)
# 3‑4. Wrap in Response, set mimetype + status code
return Response(response=json_str, status=200, mimetype="application/json")
6.2.2. Automatic JSON Responses with jsonify#
It is recommended that you use Flask’s jsonify function to return JSON since it will save yourself time, effort and avoid introducing bugs.
The jsonify function does the following for us:
Serialisation
Creates a Flask
Responseobject with the correct settings for JSON
For example:
from flask import jsonify
@app.route("/api/test")
def api_test():
payload = {
"message": "Hello, this is some JSON!",
}
return jsonify(payload)