Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 38 ยท Projects and Practice

Project: A Validated Bookshelf API

Build a small FastAPI service with Pydantic: create, list, filter and patch books, separate input and output models, consistent errors, pagination and tests through httpx.

This project builds the HTTP layer of Shelfie, the bookshelf tracker from the previous project. It is a small FastAPI service whose whole job is to be strict at the boundary: every request is validated by a model, every response is filtered by a model, and every error has the same shape. Storage is an in-memory dictionary, so you can run everything in the editor; replacing it with a database touches only one class.

Make sure you have read FastAPI Request Models, Response Models and Errors and Dependencies.

As in those lessons, endpoints are async def and the requests are sent through httpx without a network server, because the browser cannot start threads or listen on a port. The code is otherwise what you would run with fastapi dev.

The plan

flowchart TB
    C["client"] --> R["routes"]
    R --> M["request models<br/>BookCreate, BookUpdate, Filters"]
    R --> S["BookStore<br/>(in-memory)"]
    S --> O["response models<br/>BookOut, Page[BookOut]"]
    O --> C
    R -.errors.-> E["one error format"]

Models on the way in, models on the way out, one error shape.

Method Path What it does
POST /books add a book (201)
GET /books list with filters and paging
GET /books/{id} one book or 404
PATCH /books/{id} change some fields
DELETE /books/{id} remove a book (204)

Step 1: the models

Notice the three-way split: what a client may create, what it may change, and what the API returns. The read-only id and added_at exist only on the output.

Python Step 1: models and a store

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The update uses model_copy(update=...), which skips validation, then validates the final object again. That second step matters: changes that are valid alone can still produce an invalid result.

Step 2: filters and a paged response

The list endpoint takes its parameters as one model and returns a generic Page. The filter model is the same pattern as in the request-models lesson.

Python Step 2: filters and Page[T]

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Step 3: the whole API

Now the routes. One exception handler gives every error the same shape: {"error": {"code": ..., "message": ..., "fields": {...}}}.

Python Step 3: the FastAPI app and a tour

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the output of the bad request carefully. All the problems appear together, grouped by field: the missing author, the empty title, the zero pages and the forbidden isbn. A form could mark all four inputs at once.

Step 4: tests

Test the API as a client would: send requests, check status codes and JSON. A small helper keeps each test short, and a fresh app state at the start of every test keeps them independent.

Python Step 4: API tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The app is built by a function, make_app(), so each test gets its own empty storage. That "app factory" idea is the easiest way to keep API tests independent. With pytest you would call make_app() in a fixture and use TestClient or the same httpx transport.

Ideas to extend it

  • Add a GET /stats endpoint with a response model that has total pages read and average rating.
  • Add a validator that a finished book must have a rating.
  • Replace ROWS with SQLite through sqlite3 and keep the API and the tests unchanged.
  • Add authentication with a dependency that checks an API key from the settings.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does patch_book validate the merged result again?

    BookUpdate checks each changed field, but the final BookOut is validated once more so the stored record always satisfies the full model.
  2. 2. What is the benefit of one handler for RequestValidationError and HTTPException?

    A consistent error format simplifies client code and documentation.
  3. 3. Why do BookCreate, BookUpdate and BookOut exist as separate models?

    Separate models express three different contracts: what can be sent to create, what can be changed, and what is returned.
  4. 4. Why build the app with a make_app() function in tests?

    A factory avoids shared state between tests, a common cause of flaky tests.

Summary

  • Three models per resource: create, update, output; generic Page[T] for lists.
  • Forbid extra fields, validate merged results, and use exclude_unset=True for PATCH.
  • One exception handler per error family gives a consistent error format.
  • Test through the HTTP interface with a fresh app per test.

Next: Project: A Validating CSV Importer