Lab: Testing Endpoints with a Test Client
Build a small FastAPI reading-list service and test its endpoints in-process with TestClient — 2xx, 404 and 422 — injecting a fake repository through a dependency override.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: extend the units
- Step 2: write the app
- Step 3: the client fixture and the override
- Step 4: test the contract
- Step 5: look at the 422 body
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of Software Testing Fundamentals
- Why Automated Tests, and What to Test First Concept · 15 min
- Framework Essentials: Asserts, Fixtures and Parametrized Cases (pytest or Vitest) Worked example · 25 min
- Fakes, Stubs and Mocks Without Over-Mocking Concept · 20 min
- Lab: Testing Endpoints with a Test Client Lab · 25 min
- Reading Coverage and Choosing Test Levels Worked example · 15 min
- Check: Find the Missing Test Knowledge check · 8 questions
What you will learn
- Write in-process endpoint tests for a web endpoint or other entry point, asserting on its observable outputs (status, headers, body or return value).
- Write unit tests with a unit-test framework (pytest in the reference stack, Vitest for JavaScript/TypeScript) using arrange-act-assert, parametrized cases and shared fixtures, including tests for error paths.
Prerequisites: Python Foundations
01. Goal and setup
Unit tests guard your helpers; users, however, meet endpoints. This lab builds a two-route reading-list service and tests it at the boundary clients actually touch: send a request, assert on the status code, headers and body. No server is started and no port is opened — FastAPI's TestClient drives the whole request path inside your test process, so routing, validation and serialisation all run for real.
The suite will prove the contract of POST /books and GET /books/{slug}: a 201 with a generated slug, a 200 with the stored book, a 404 for an unknown slug, and a 422 when validation rejects the body. The fake repository from the doubles lesson is injected through a dependency override, the seam FastAPI provides exactly for tests.
This lab was run with Python 3.12.13, FastAPI 0.163.1 (with Starlette 1.10.0 and Pydantic 2.14.3), pytest 9.2.0, and httpx2 2.16.2 for the test client. Set up the lab in a scratch folder:
uv venv --python 3.12 .venv
uv pip install --python .venv/bin/python fastapi==0.163.1 \
pytest==9.2.0 httpx2==2.16.2readinglist/
├── pyproject.toml [tool.pytest.ini_options]: testpaths, pythonpath = ["."]
├── app/
│ ├── validation.py + make_slug in this lab
│ ├── repository.py new: Book, BookRepository, InMemoryBookRepository
│ └── main.py new: the FastAPI app and its two routes
└── tests/
├── conftest.py + repo and client fixtures
├── test_validation.py from the previous lesson
├── test_slug.py new: unit tests for make_slug
└── test_api.py new: endpoint tests02. Step 1: extend the units
Two new pieces of pure logic come before any endpoint: the slug builder, and the repository types. Append make_slug to app/validation.py, and create app/repository.py with the interface the app will depend on plus its in-memory fake:
def make_slug(title: str) -> str:
"""Turn a title into a lowercase, hyphen-separated slug."""
slug = re.sub(r"[^a-z0-9]+", "-", normalise_title(title).lower()).strip("-")
if not slug:
raise InvalidInput("title has no letters or digits to build a slug from")
return slugfrom dataclasses import dataclass
@dataclass(frozen=True)
class Book:
title: str
author: str
slug: str
class BookRepository:
"""What the app depends on. The real one talks to PostgreSQL."""
def add(self, book: Book) -> None:
raise NotImplementedError
def all(self) -> list[Book]:
raise NotImplementedError
class InMemoryBookRepository(BookRepository):
"""A fake: the same behaviour, backed by a plain list."""
def __init__(self) -> None:
self._books: list[Book] = []
def add(self, book: Book) -> None:
self._books.append(book)
def all(self) -> list[Book]:
return list(self._books)import pytest
from app.validation import InvalidInput, make_slug
@pytest.mark.parametrize(
("title", "expected"),
[
("The Pragmatic Programmer", "the-pragmatic-programmer"),
("Refactoring, 2nd edition!", "refactoring-2nd-edition"),
("Gödel, Escher, Bach", "g-del-escher-bach"),
],
)
def test_make_slug_builds_url_friendly_slugs(title: str, expected: str) -> None:
assert make_slug(title) == expected
def test_make_slug_rejects_titles_without_letters_or_digits() -> None:
with pytest.raises(InvalidInput, match="no letters or digits"):
make_slug("!!!")18 passed in 0.32sEighteen tests: the fourteen validation tests from the previous lesson plus these four. Note the third case: the slug alphabet is ASCII letters and digits, so Gödel becomes g-del. That is a deliberate simplification to keep URLs stable, and the test documents it. Unit level, these cost fractions of a second — the endpoint tests that follow will lean on make_slug being correct.
03. Step 2: write the app
The app depends on BookRepository through a dependency function. Production wiring returns the shared repository; in the next step the test swaps that function for one returning a fresh fake. Create app/main.py:
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from pydantic import BaseModel, Field
from app.repository import Book, BookRepository, InMemoryBookRepository
from app.validation import make_slug, normalise_title
class BookIn(BaseModel):
title: str = Field(min_length=1, max_length=200)
author: str = Field(min_length=1, max_length=200)
class BookOut(BaseModel):
title: str
author: str
slug: str
app = FastAPI(title="Reading List")
_SHARED_REPO = InMemoryBookRepository()
def get_repository() -> BookRepository:
"""Production wiring; tests swap it for a fresh fake per test."""
return _SHARED_REPO
@app.post("/books", response_model=BookOut, status_code=status.HTTP_201_CREATED)
def create_book(
payload: BookIn, repo: Annotated[BookRepository, Depends(get_repository)]
) -> Book:
title = normalise_title(payload.title)
slug = make_slug(title)
if any(book.slug == slug for book in repo.all()):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT, detail="book already in the list"
)
book = Book(title=title, author=payload.author, slug=slug)
repo.add(book)
return book
@app.get("/books/{slug}", response_model=BookOut)
def read_book(
slug: str, repo: Annotated[BookRepository, Depends(get_repository)]
) -> Book:
for book in repo.all():
if book.slug == slug:
return book
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="book not found"
)Four details matter for testing. status_code=201 on the decorator makes success explicit rather than the default 200. BookIn declares the request contract, and FastAPI validates it before your handler runs. The handlers return the stored Book dataclass, and response_model=BookOut tells FastAPI to validate and serialise it into the response shape. The repo parameter, declared as Annotated[BookRepository, Depends(get_repository)], is the seam: FastAPI calls get_repository() for each request and passes the result in. Annotated is the style the FastAPI docs recommend; the older repo: BookRepository = Depends(get_repository) form still works.
04. Step 3: the client fixture and the override
Extend tests/conftest.py (keep the tidy_titles fixture from before, and move the new imports up to join the existing ones). The repo fixture builds a fresh fake per test. The client fixture registers a dependency override — a mapping from the original dependency function to a replacement — then yields a TestClient bound to the app, and clears the override afterwards:
from collections.abc import Iterator
import pytest
from fastapi.testclient import TestClient
from app.main import app, get_repository
from app.repository import BookRepository, InMemoryBookRepository
@pytest.fixture
def repo() -> BookRepository:
return InMemoryBookRepository()
@pytest.fixture
def client(repo: BookRepository) -> Iterator[TestClient]:
app.dependency_overrides[get_repository] = lambda: repo
with TestClient(app) as test_client:
yield test_client
app.dependency_overrides.clear()Both fixtures have function scope, so every test gets its own empty repository and its own client; no book added by one test can leak into another, and clearing the override protects any later test that wants the real wiring. Because the client is a fixture, a test that needs a prefilled repository can request repo, add books directly, and still receive the same instance through the override.
05. Step 4: test the contract
Now the endpoint tests. Each names the behaviour in its title: the status code, and what the body promises. The first test also checks the full response body, which pins the wire format — including the title coming back normalised. Run them with .venv/bin/pytest -v tests/test_api.py:
from fastapi.testclient import TestClient
def test_create_book_answers_201_with_a_slug(client: TestClient) -> None:
response = client.post(
"/books",
json={"title": "The Pragmatic Programmer", "author": "Hunt & Thomas"},
)
assert response.status_code == 201
assert response.json() == {
"title": "The Pragmatic Programmer",
"author": "Hunt & Thomas",
"slug": "the-pragmatic-programmer",
}
def test_read_book_answers_200_with_the_stored_book(client: TestClient) -> None:
created = client.post(
"/books", json={"title": "Refactoring", "author": "Martin Fowler"}
).json()
response = client.get(f"/books/{created['slug']}")
assert response.status_code == 200
assert response.json() == created
def test_read_unknown_book_answers_404(client: TestClient) -> None:
response = client.get("/books/unknown-slug")
assert response.status_code == 404
assert response.json() == {"detail": "book not found"}
def test_empty_title_answers_422(client: TestClient) -> None:
response = client.post(
"/books", json={"title": "", "author": "Martin Fowler"}
)
assert response.status_code == 422
assert "detail" in response.json()tests/test_api.py::test_create_book_answers_201_with_a_slug PASSED [ 25%]
tests/test_api.py::test_read_book_answers_200_with_the_stored_book PASSED [ 50%]
tests/test_api.py::test_read_unknown_book_answers_404 PASSED [ 75%]
tests/test_api.py::test_empty_title_answers_422 PASSED [100%]The assertions target only what crosses the boundary: status, body, and headers if you use them. What the handler does internally — which exception type it raised, which method of the fake it called — is invisible to clients and belongs to no endpoint test. The whole suite, run with .venv/bin/pytest -q, now stands at 22 tests:
22 passed in 1.79s06. Step 5: look at the 422 body
The 422 in the last test came from Pydantic, before create_book ran at all: min_length=1 rejected the empty title. FastAPI's validation errors are structured, and knowing the shape helps you assert on it precisely when a client needs to. Here is the real body the test received:
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
response = client.post("/books", json={"title": "", "author": "Fowler"})
print(response.status_code, response.json())422 {'detail': [{'type': 'string_too_short', 'loc': ['body', 'title'],
'msg': 'String should have at least 1 character', 'input': '',
'ctx': {'min_length': 1}}]}The loc array names the failing field, msg explains the rule, and ctx carries the constraint. A client can turn this into a form message without guessing. The next lesson runs a branch-coverage report over everything you wrote today and shows one branch this suite quietly leaves untested.
07. Check your understanding
08. Apply it: stretch tasks
Continue the practice task for this skill:
- Add a
GET /bookscollection route returning every stored book as a list, with one endpoint test asserting the empty case (200and[]) and one asserting two books after two posts. - Assert on a response header: the
201carries acontent-typeofapplication/json— checkresponse.headers["content-type"]. - On a JavaScript stack, test a Next.js route handler the same way: call
GET(new Request("http://localhost/books"))directly under Vitest and assert on theResponseit returns, with your fake repository injected as a parameter or module seam.
09. Review prompt
Without looking back: explain what TestClient runs and what it skips, and why an endpoint test asserts on status and body rather than internals. Describe what a dependency override replaces and when yours is cleared. Finally, say where a 422 comes from in this app, and what turns a domain error into a 500 instead.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.