A REST API with FastAPI and tests
Python Development Lab
Project description
The participant learns to turn an API specification into tested code with the help of an agent and the fastapi-router-py skill.
Tools used
The agent can be replaced with any similar coding agent; the steps are written so that they do not depend on a single tool.
Requirements
- Python 3.10+
- fastapi
- uvicorn
- pytest
- httpx
Steps
Set up the environment
Create a virtual environment and install the packages.
Code / commandspython -m venv .venv pip install fastapi uvicorn pytest httpxGenerate the endpoints
Ask for the endpoints together with the Pydantic models.
Prompt for this stepCreate a FastAPI API for managing tasks ...Testing
Run the tests and open /docs.
Prompt for this stepWrite pytest tests ...Code / commandspytest -q
Ready-made prompts
Create a FastAPI API for managing tasks: GET /tasks, POST /tasks, PATCH /tasks/{id} and DELETE /tasks/{id}. Use Pydantic models for validation, and store the data in memory for now.Write pytest tests with fastapi.testclient.TestClient that cover every endpoint, including the 404 case.An example of the resulting code
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class TaskIn(BaseModel):
title: str
done: bool = False
class Task(TaskIn):
id: int
TASKS: dict[int, Task] = {}
@app.post("/tasks", status_code=201)
def create(t: TaskIn) -> Task:
task = Task(id=len(TASKS) + 1, **t.model_dump())
TASKS[task.id] = task
return task
@app.get("/tasks/{task_id}")
def read(task_id: int) -> Task:
if task_id not in TASKS:
raise HTTPException(404, "Task not found")
return TASKS[task_id]An illustrative example of what the agent is expected to produce; the actual output may differ, so always review and test it.
Tests
- pytest -q
- uvicorn main:app --reload, then open /docs
Expected results
- Interactive documentation at /docs
- Passing tests for every endpoint
Common mistakes and their fixes
| Mistake | Fix |
|---|---|
| Using dict() in Pydantic v2 | Use model_dump() |
