Skip to content
devtoolbox.cc

FastAPI · Chapter 5 of 6

FastAPI CRUD API: routers, dependencies, 404, 409, PATCH

15 min study · Examples checked with FastAPI 0.163 on Python 3.14 ·

The previous chapters covered the pieces of a request and a response. This one puts them together into a complete API for lessons with the four classic operations: create, read, update and delete (CRUD). The data lives in memory for now, behind a small storage class that chapter 6 replaces with a database without touching the routes. Along the way, the chapter introduces two features every larger FastAPI project uses: routers, which group endpoints, and dependencies, which hand shared objects to handlers.

The whole API

from typing import Annotated

from fastapi import APIRouter, Depends, FastAPI, HTTPException, Query, Response, status
from pydantic import BaseModel, ConfigDict, Field


class LessonIn(BaseModel):
    model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
    title: str = Field(min_length=3, max_length=120)
    minutes: int = Field(ge=1, le=180)


class LessonPatch(BaseModel):
    model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
    title: str | None = Field(default=None, min_length=3, max_length=120)
    minutes: int | None = Field(default=None, ge=1, le=180)


class LessonOut(LessonIn):
    id: int


class LessonStore:
    def __init__(self) -> None:
        self._rows: dict[int, LessonOut] = {}
        self._next_id = 1

    def list(self, offset: int, limit: int) -> list[LessonOut]:
        return list(self._rows.values())[offset : offset + limit]

    def get(self, lesson_id: int) -> LessonOut:
        if lesson_id not in self._rows:
            raise HTTPException(status_code=404, detail="Lesson not found")
        return self._rows[lesson_id]

    def save(self, lesson_id: int | None, data: LessonIn) -> LessonOut:
        title = data.title.casefold()
        if any(r.title.casefold() == title and r.id != lesson_id for r in self._rows.values()):
            raise HTTPException(status_code=409, detail="A lesson with this title exists")
        if lesson_id is None:
            lesson_id, self._next_id = self._next_id, self._next_id + 1
        self._rows[lesson_id] = LessonOut(id=lesson_id, **data.model_dump())
        return self._rows[lesson_id]

    def delete(self, lesson_id: int) -> None:
        self.get(lesson_id)
        del self._rows[lesson_id]


store = LessonStore()


def get_store() -> LessonStore:
    return store


Store = Annotated[LessonStore, Depends(get_store)]
router = APIRouter(prefix="/lessons")


@router.get("")
def list_lessons(
    db: Store,
    offset: Annotated[int, Query(ge=0)] = 0,
    limit: Annotated[int, Query(ge=1, le=100)] = 20,
) -> list[LessonOut]:
    return db.list(offset, limit)


@router.post("", status_code=status.HTTP_201_CREATED)
def create_lesson(data: LessonIn, db: Store, response: Response) -> LessonOut:
    lesson = db.save(None, data)
    response.headers["Location"] = f"/lessons/{lesson.id}"
    return lesson


@router.get("/{lesson_id}")
def read_lesson(lesson_id: int, db: Store) -> LessonOut:
    return db.get(lesson_id)


@router.patch("/{lesson_id}")
def update_lesson(lesson_id: int, patch: LessonPatch, db: Store) -> LessonOut:
    changes = patch.model_dump(exclude_unset=True)
    if any(value is None for value in changes.values()):
        raise HTTPException(status_code=422, detail="Fields cannot be set to null")
    current = db.get(lesson_id)
    merged = LessonIn(**(current.model_dump(exclude={"id"}) | changes))
    return db.save(lesson_id, merged)


@router.delete("/{lesson_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_lesson(lesson_id: int, db: Store) -> None:
    db.delete(lesson_id)


app = FastAPI(title="Study Tracker API")
app.include_router(router)

Three models describe the data. LessonIn is what clients send to create a lesson, LessonPatch is a partial change where every field is optional, and LessonOut adds the server-assigned id. LessonStore holds the rows and enforces the rules: a missing ID is a 404, and two lessons may not share a title, ignoring case, which is a 409.

Routers group endpoints

An APIRouter collects related routes under a common prefix. @router.get("") with prefix="/lessons" serves GET /lessons, and @router.get("/{lesson_id}") serves GET /lessons/3. The router does nothing until app.include_router(router) attaches it. In a bigger project each resource gets its own module with its own router (lessons.py, courses.py, users.py), and main.py only creates the app and includes them.

Dependencies hand shared objects to handlers

Depends(get_store) tells FastAPI: before calling this handler, call get_store() and pass the result in. Store = Annotated[LessonStore, Depends(get_store)] gives that declaration a short name, so each handler just takes db: Store. This indirection is the point. Handlers don’t reach for a global variable, and anything a handler needs (a database session, the current user, settings) arrives the same way. Dependencies can themselves depend on others and on request data, and FastAPI resolves the whole chain per request.

It also makes testing easy. app.dependency_overrides[get_store] = lambda: LessonStore() swaps in a fresh, empty store for tests, so each test starts clean and no test touches real data. The next chapter’s database session is injected with exactly the same mechanism.

Create and read

POST /lessons validates the body, saves it, and returns 201 with the new lesson and a Location header pointing at it:

POST /lessons {"title": "Variables", "minutes": 20}
201 {"title": "Variables", "minutes": 20, "id": 1}    location: /lessons/1

POST /lessons {"title": "LOOPS", "minutes": 5}        (after "Loops" was created)
409 {"detail": "A lesson with this title exists"}

GET /lessons?offset=1&limit=1
200 [{"title": "Loops", "minutes": 25, "id": 2}]

The duplicate check runs on the server even if a client checked first, because two clients can submit the same title at nearly the same time. With a database, a unique constraint makes that check reliable. The in-memory version is only safe while one worker process handles requests.

The list endpoint never returns everything at once. offset and limit page through the results, and le=100 caps the page size so one request cannot ask for a million rows. Clients get stable pages only if the order is stable, which a database query guarantees with ORDER BY.

Update: PUT replaces, PATCH changes

PUT /lessons/{id} conventionally replaces the whole resource, so its body is a full LessonIn; a PUT without minutes would fail validation rather than silently keep the old value. This API offers PATCH instead, which changes only what the client sends: {"minutes": 30} returns the lesson with the new duration and its old title, while {"title": null} gets 422 Fields cannot be set to null.

The handler takes model_dump(exclude_unset=True), so fields the client left out are untouched. It rejects explicit null for fields that can’t be empty, then merges the change into the current values and validates the result as a complete LessonIn. That last step matters: rules that involve several fields, and the duplicate-title check, run on the merged lesson, not just on the patch.

Delete

DELETE /lessons/1 returns 204 with an empty body. A second delete of the same ID returns 404, since there is nothing to delete. Some APIs return 204 there too; document whichever you choose. The handler’s return type is None, and FastAPI sends no body for a 204.

Why memory is not enough

The store suits learning and tests, but data disappears on every restart. A production server usually runs several worker processes, and each would have its own separate dictionary, so a lesson created through one worker would be invisible to the next request handled by another. Concurrent requests can also interleave between the duplicate check and the insert. A database solves all three problems, which is the topic of the next chapter.

Practice

Add a PUT /lessons/{lesson_id} that replaces a lesson (404 if it doesn’t exist) and a GET /lessons?q= filter that matches titles case-insensitively. Write tests that use app.dependency_overrides to give every test its own empty store.

Answer check: PUT takes a LessonIn, calls db.get(lesson_id) first for the 404, then db.save(lesson_id, data), so a rename to an existing title still gets the 409. For the filter, add q: str | None = None and filter title.casefold() before slicing with offset and limit. A pytest fixture that sets the override and clears it afterwards keeps tests independent.

Summary

Group a resource’s endpoints in an APIRouter, and inject shared objects such as storage with Depends, which tests can override. Return 201 with a Location header on create, 404 for missing IDs, 409 for conflicts and 204 on delete. Page lists with bounded offset and limit, and implement PATCH by merging only the sent fields and validating the merged result.

All FastAPI chapters