Return JSON response from Flask view

Code Ninja picture Code Ninja · Oct 26, 2012 · Viewed 549.6k times · Source

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

Answer

codegeek picture codegeek · Oct 26, 2012

Pass the summary data to the jsonify function, which returns a JSON response.

from flask import jsonify

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

As of Flask 0.11, you can pass any JSON-serializable type, not just dict, as the top level object.