Flask JSON Responses
A JSON response sends data instead of a page. The jsonify call turns a dict into JSON.
Make the app
This line imports Flask and jsonify together. The route below returns JSON.
from flask import Flask, jsonify
app = Flask(__name__)Return a user as JSON
The view passes a dict to jsonify. Flask turns it into a JSON response.
@app.route("/user")
def user():
return jsonify({"name": "Ana", "score": 9})Read the JSON back
The test client asks for /user. get_json turns the JSON response back into a dict.
client = app.test_client()
print(client.get("/user").get_json())Example
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/user")
def user():
return jsonify({"name": "Ana", "score": 9})
client = app.test_client()
print(client.get("/user").get_json())Key points
- jsonify turns a dict into a JSON response.
- The response carries the right content type for JSON.
- Read JSON back with .get_json() on the test response.
- Use JSON responses for data, not for pages.
In this example, the view passes a dict to jsonify, and Flask sends it as a JSON response. The test client asks for /user, and get_json turns the response back into a dict for the print.
Note
jsonify takes a dict, like a Python dict.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does jsonify({"name": "Ana"}) return?