A REST API with FastAPI and tests

Python Development Lab

Python development labLevel: Intermediate Duration: Two hours

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

  1. Set up the environment

    Create a virtual environment and install the packages.

    Code / commands
    python -m venv .venv
    pip install fastapi uvicorn pytest httpx
  2. Generate the endpoints

    Ask for the endpoints together with the Pydantic models.

    Prompt for this step
    Create a FastAPI API for managing tasks ...
  3. Testing

    Run the tests and open /docs.

    Prompt for this step
    Write pytest tests ...
    Code / commands
    pytest -q

Ready-made prompts

The specification
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.
Tests
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

MistakeFix
Using dict() in Pydantic v2Use model_dump()

Documentation links