Flask Working with JSON Return a JSON Response from Flask API


Flask has a utility called jsonify() that makes it more convenient to return JSON responses

from flask import Flask, jsonify

app = Flask(__name__)

def hello():
    return jsonify(hello='world') # Returns HTTP Response with {"hello": "world"}

Try it with curl

curl -X GET
  "hello": "world"

Other ways to use 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)