Flask has a utility called jsonify()
that makes it more convenient to return JSON responses
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/get-json')
def hello():
return jsonify(hello='world') # Returns HTTP Response with {"hello": "world"}
curl
curl -X GET http://127.0.0.1:5000/api/get-json
{
"hello": "world"
}
jsonify()
Using an existing dictionary:
person = {'name': 'Alice', 'birth-year': 1986}
return jsonify(person)
Using a list:
people = [{'name': 'Alice', 'birth-year': 1986},
{'name': 'Bob', 'birth-year': 1985}]
return jsonify(people)