Fix Python – Return JSON response from Flask view

Question

Asked By – Code Ninja

I have a function that analyzes a CSV file with Pandas and produces a dict with summary information. I want to return the results as a response from a Flask view. How do I return a JSON response?

@app.route("/summary")
def summary():
    d = make_summary()
    # send it back as json

Now we will see solution for issue: Return JSON response from Flask view


Answer

As of Flask 1.1.0 a view can directly return a Python dict and Flask will call jsonify automatically.

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

If your Flask version is less than 1.1.0 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)

This question is answered By – codegeek

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0