Returning JSON Responses in Flask Views
When working with Flask views, the return value determines how the response is formatted. To return a JSON response, Flask provides the following options:
Option 1: JSON Serialization
Flask automatically serializes Python dictionaries or lists into JSON responses. To implement this:
@app.route("/summary") def summary(): d = make_summary() return d
Option 2: jsonify Function
For older Flask versions or when returning custom JSON-serializable objects, use the jsonify function:
from flask import jsonify @app.route("/summary") def summary(): d = make_summary() return jsonify(d)
Both options effortlessly return the specified data as a JSON response, allowing for seamless integration with frontend applications.
The above is the detailed content of How to Return JSON Responses in Flask Views?. For more information, please follow other related articles on the PHP Chinese website!