Return JSON response from Flask view

ghz 1years ago ⋅ 3045 views

Question

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

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)