Returning JSON Responses from Flask Views
In Flask, views can conveniently return data in a JSON format, allowing seamless integration with front-end applications. Let's explore how this is achieved.
To return a JSON response, the view function can directly return a Python dictionary or list, and Flask will automatically convert it to JSON using its jsonify function. For example:
@app.route("/summary") def summary(): d = make_summary() return d
This approach is suitable for recent Flask versions. For older versions, or if you need more control over the JSON serialization process, you can import the jsonify function and use it explicitly:
from flask import jsonify @app.route("/summary") def summary(): d = make_summary() return jsonify(d)
Using jsonify allows for custom JSON handling, such as specifying custom serializers or using JSONP. Here are some additional examples:
# Customizing JSON serialization return jsonify({'foo': 'bar'}, {'_custom': lambda obj: obj.CustomFooSerializer() }) # JSONP response with callback parameter return jsonify(foo='bar'), 200, {'jsonp':'myCallback'}
By returning JSON responses from Flask views, developers can easily create RESTful APIs or provide data in a consistent and consumable format for client applications.
The above is the detailed content of How Can I Return JSON Responses from Flask Views?. For more information, please follow other related articles on the PHP Chinese website!