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:

  1. Serialise (convert) your Python data, usually a dict, to a JSON‑encoded str.

  2. Wrap that string in a flask.Response object.

  3. Set the correct Content‑Type header (application/json; charset=utf-8).

  4. (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:

  1. Serialisation

  2. Creates a Flask Response object 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)