Simple API Exercises
These exercises put everything together — Flask, PookieDB, and JavaScript fetch — the full picture.
Exercise 1 — Your First JSON Endpoint
In your patient Flask app, add a /patients route that returns all patients as JSON using jsonify. Run the app and visit http://127.0.0.1:5000/patients in the browser. Confirm you see JSON — not an HTML page.
Exercise 2 — Single Patient Endpoint
Add a /patients/<int:id> route that returns one patient by their id.
Test it by visiting /patients/1, /patients/2, and then a number that has no matching patient. What does Flask do when Patient.objects.get(id=id) finds nothing? Add a check — if the patient does not exist, return { "error": "not found" } instead of crashing.
Exercise 3 — Fetch on the Frontend
Create a fresh templates/index.html with no Jinja2. Just a button labelled "Load Patients" and a Bootstrap-styled table with an empty <tbody>.
When the button is clicked, call loadPatients() — a function that fetches from /patients and builds the table rows from the data. The page should never reload.
Exercise 4 — Add a Patient Without a Page Reload
Add a form to the template with a name and age field and an "Add Patient" button. When clicked, instead of submitting the form the normal way, use fetch() to send the data to a new Flask route /patients/add that accepts POST requests and saves the new patient to the database.
On the Flask side, receive the data like this:
from flask import Flask, jsonify, request
import json
@app.route('/patients/add', methods=['POST'])
def add_patient():
data = request.get_json()
Patient.objects.create(name=data["name"], age=int(data["age"]))
return jsonify({ "status": "ok" })
On the JavaScript side, send the data like this:
function addPatient() {
// read the input values
let nameInput = document.getElementById("name")
let ageInput = document.getElementById("age")
let name = nameInput.value
let age = ageInput.value
fetch("/patients/add", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: name, age: age })
})
.then(function(response) {
return response.json()
})
.then(function(result) {
// after adding, reload the table to show the new patient
loadPatients()
})
}
Get this working — add a patient using the form and watch the table update without a single page reload.
Info
Exercise 4 is how most modern web apps work. The form, the data transfer, and the table update all happen through JavaScript. Flask handles the data and the database. Neither side needs to know much about the other — they just talk through JSON.