Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return JSON response from Flask view

Tags:

python

json

flask

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 
like image 809
Code Ninja Avatar asked Oct 26 '12 05:10

Code Ninja


People also ask

How do I return status code and JSON in Flask?

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.


1 Answers

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) 
like image 162
codegeek Avatar answered Oct 07 '22 00:10

codegeek