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
To send JSON and status code with a Python Flask response, we can return a tuple with the response body and the status code in our view. to add the login view with the response returned. We return the body with jsonify(data) and we return the status code by putting 200 in the same tuple.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With