The Python Oracle

Return JSON response from Flask view

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop

--

Chapters
00:00 Question
00:28 Accepted answer (Score 983)
01:02 Answer 2 (Score 286)
01:31 Answer 3 (Score 156)
02:01 Answer 4 (Score 51)
02:44 Thank you

--

Full question
https://stackoverflow.com/questions/1308...

Accepted answer links:
[jsonify]: https://flask.palletsprojects.com/api/#f...
[jsonify]: https://flask.palletsprojects.com/api/#f...

Answer 3 links:
[flask.jsonify]: http://flask.pocoo.org/docs/latest/api/#...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #json #flask

#avk47



ACCEPTED ANSWER

Score 1024


A view can directly return a Python dict or list and Flask will call jsonify automatically.

@app.route("/summary")
def summary():
    d = make_summary()
    return d

For older Flask versions, or to return a different JSON-serializable object, import and use jsonify.

from flask import jsonify

@app.route("/summary")
def summary():
    d = make_summary()
    return jsonify(d)



ANSWER 2

Score 292


jsonify serializes the data you pass it to JSON. If you want to serialize the data yourself, do what jsonify does by building a response with status=200 and mimetype='application/json'.

from flask import json

@app.route('/summary')
def summary():
    data = make_summary()
    response = app.response_class(
        response=json.dumps(data),
        status=200,
        mimetype='application/json'
    )
    return response



ANSWER 3

Score 165


Pass keyword arguments to flask.jsonify and they will be output as a JSON object.

@app.route('/_get_current_user')
def get_current_user():
    return jsonify(
        username=g.user.username,
        email=g.user.email,
        id=g.user.id
    )
{
    "username": "admin",
    "email": "admin@localhost",
    "id": 42
}

If you already have a dict, you can pass it directly as jsonify(d).




ANSWER 4

Score 53


If you don't want to use jsonify for some reason, you can do what it does manually. Call flask.json.dumps to create JSON data, then return a response with the application/json content type.

from flask import json

@app.route('/summary')
def summary():
    data = make_summary()
    response = app.response_class(
        response=json.dumps(data),
        mimetype='application/json'
    )
    return response

flask.json is distinct from the built-in json module. It will use the faster simplejson module if available, and enables various integrations with your Flask app.