CompCode Academy

Lesson 5 of 6 · Free to read

Lab: fix a broken API with AI as your pair

Lab: fix a broken API with AI as your pair

Audience: Final-year students and engineers in their first three years
Prerequisites: Lessons 1–4. Python 3.10 or newer (tested on 3.13), and any AI coding tool.
Time: about 75 minutes
What you will keep: a small API with all tests passing, and a PROMPTS.md with at least six entries
This lesson does not cover: deploying the API.

The task

Below is a small task-tracker API with four bugs. Six tests describe the correct behaviour; four of them fail. Your job is to get all six passing with an AI tool as your pair-programmer, and to log the prompts that mattered.

The rule for this lab: read the failing test before you prompt. People who diagnose first usually finish faster than people who paste the error and hope.

Set up (10 minutes)

Create a folder called task-api with this layout:

task-api/
  requirements.txt
  app/__init__.py        (empty file)
  app/main.py
  tests/__init__.py      (empty file)
  tests/test_tasks.py

requirements.txt (these versions were tested together):

fastapi==0.162.0
pydantic==2.14.1
pytest==9.1.1
httpx==0.28.1

app/main.py:

from datetime import date

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()
TASKS: list[dict] = []


class TaskIn(BaseModel):
    title: str
    due: date
    done: bool = False


@app.post("/tasks", status_code=201)
def create_task(task: TaskIn):
    row = {"id": len(TASKS) + 1, **task.model_dump()}
    TASKS.append(row)
    return row


@app.get("/tasks")
def list_tasks(offset: int = 0, limit: int = 10):
    return TASKS[offset : offset + limit + 1]


@app.get("/tasks/overdue")
def overdue(today: date):
    return [t for t in TASKS if not t["done"] and t["due"] > today]


@app.get("/tasks/stats")
def stats():
    done = sum(1 for t in TASKS if t["done"])
    return {"total": len(TASKS), "percent_done": round(100 * done / len(TASKS))}


@app.get("/tasks/{task_id}")
def get_task(task_id: int):
    for t in TASKS:
        if t["id"] == task_id:
            return t
    raise HTTPException(status_code=404, detail="Task not found")

tests/test_tasks.py:

import pytest
from fastapi.testclient import TestClient

from app.main import TASKS, app

client = TestClient(app)


@pytest.fixture(autouse=True)
def empty_store():
    TASKS.clear()


def add(title="Write tests", due="2026-11-01", done=False):
    return client.post("/tasks", json={"title": title, "due": due, "done": done})


def test_create_and_fetch():
    assert add().status_code == 201
    assert client.get("/tasks/1").json()["title"] == "Write tests"


def test_empty_title_is_rejected():
    assert add(title="").status_code == 422


def test_page_size_is_respected():
    for i in range(5):
        add(title=f"Task {i}")
    assert len(client.get("/tasks?offset=0&limit=2").json()) == 2


def test_overdue_means_due_before_today():
    add(title="Old", due="2026-10-01")
    add(title="Future", due="2026-12-01")
    titles = [t["title"] for t in client.get("/tasks/overdue?today=2026-10-27").json()]
    assert titles == ["Old"]


def test_stats_with_no_tasks():
    assert client.get("/tasks/stats").json() == {"total": 0, "percent_done": 0}


def test_missing_task_is_404():
    assert client.get("/tasks/99").status_code == 404

Install and run the tests from inside task-api:

python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install -r requirements.txt
python -m pytest -q

You should see 4 failed, 2 passed. A deprecation warning from the test client may also appear; it does not affect this lab.

Work the bugs (50 minutes)

For each failing test:

  1. Read the test and the error. Write your own guess at the cause in PROMPTS.md before prompting.
  2. Prompt with a pattern from lesson 2. Start with Specify: the test name, the error, and "list likely causes, no fix yet".
  3. Ask for the smallest fix, limited to the function involved (Constrain).
  4. Run the tests yourself. Log the result and your decision.
  5. If the AI changed anything else, reject that part.

Watch for the failure modes from lesson 3. If the AI suggests a pydantic option you have not seen, check that it exists in pydantic 2 before accepting it.

Definition of done

  • python -m pytest -q shows 6 passed.
  • PROMPTS.md has at least six entries, each with a Decision line.
  • Each fix is the smallest change that makes its test pass, with no unrelated edits.
  • You can explain every changed line without looking at the chat.
  • One entry says where you chose not to use AI, and why.

Stretch

Add DELETE /tasks/{task_id} that returns 204, or 404 for a missing id. Write the two tests first, then use one Specify prompt and see how close the first answer gets.

Key points

  • Diagnose first, then prompt.
  • One bug, one small fix, one test run.
  • The log is part of the deliverable, not an extra.

New free lessons and course updates. Unsubscribe from any email.