Building a JSON API with Flask
A Flask route that returns JSON is an API endpoint. You already know how to write routes — the only new thing is returning JSON instead of an HTML template.
jsonify
Flask has a built-in function called jsonify. You pass it a Python list or dictionary and it converts it into a proper JSON response:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/patients')
def get_patients():
patients = [
{ "name": "Alice", "age": 24 },
{ "name": "Bob", "age": 31 },
{ "name": "Carol", "age": 19 }
]
return jsonify(patients)
if __name__ == '__main__':
app.run(debug=True)
Run this and visit http://127.0.0.1:5000/patients in your browser. Instead of an HTML page, you get JSON. That route is now an API endpoint.
Connecting to PookieDB
Instead of a hardcoded list, pull real data from the database:
from flask import Flask, jsonify
from database import Patient
app = Flask(__name__)
@app.route('/patients')
def get_patients():
patients = Patient.objects.all()
result = []
for patient in patients:
result.append({ "name": patient.name, "age": patient.age })
return jsonify(result)
if __name__ == '__main__':
app.run(debug=True)
You loop through the PookieDB results, build a plain Python list of dictionaries, and pass that to jsonify. The browser receives structured JSON of your real patient data.
A single-item endpoint
An API usually has more than one URL. You can add a route that returns just one patient by their id:
@app.route('/patients/<int:id>')
def get_patient(id):
patient = Patient.objects.get(id=id)
return jsonify({ "name": patient.name, "age": patient.age })
<int:id> in the route captures the number from the URL and passes it to the function as id. Visit /patients/1 and id is 1. Visit /patients/3 and id is 3.
Challenge
Add the /patients route to your patient Flask app. Run it and visit the URL in your browser — do you see JSON? Then add the /patients/<int:id> endpoint and test it by visiting /patients/1, /patients/2, and a number that does not exist in your database. What happens with the one that does not exist?