Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 20 min · revision 2

Dependencies: Sharing Resources Without Globals

Extract paging rules and per-request resources into dependency functions, learn when yield dependencies open and close, and swap one out in a test without touching the route.

Contentsand lesson path

What you will learn

  • Provide shared resources and cross-cutting checks through dependencies, and override a dependency in a test.

Prerequisites: HTTP & APIs

01. The problem: rules and resources that several routes need

The reading-list API now has several routes that page through results, and soon it will hold a database session and an authenticated user per request. You could copy the paging logic into every handler and store the session in a module-level global — both work, and both rot: the copies drift apart, and the global is shared by every request at once and cannot be replaced in a test.

A dependency is the third way: a plain function that FastAPI calls before your handler, whose return value is injected as a parameter. Rules live in one place, resources are created per request and closed afterwards, and any dependency can be swapped in a test with one line. This lesson builds both kinds against the reading list, then proves the swap.

02. Step 1: shared rules as a dependency

Paging needs the same treatment everywhere: two integers, both bounded, one capped by a maximum page size. Write it once as a function, then build a reusable type alias with Annotated. Every handler that declares the alias gets validated, bounded paging — and the route signature stays readable.

Python · deps.py
from collections.abc import Iterator
from typing import Annotated

from fastapi import Depends, Query
from pydantic import BaseModel

EVENTS: list[str] = []


class Page(BaseModel):
    limit: int
    offset: int


def page_params(
    limit: Annotated[int, Query(ge=1, le=50)] = 10,
    offset: Annotated[int, Query(ge=0)] = 0,
) -> Page:
    EVENTS.append('page solved')
    return Page(limit=limit, offset=offset)


PageParams = Annotated[Page, Depends(page_params)]

page_params looks like a path operation but is never routed: Depends(page_params) marks it as something to call first. Its own parameters are read from the query string exactly as a handler’s would be, constraints included, so a limit of 500 or abc is rejected with 422 before any handler runs. The PageParams alias is the modern idiom: one import, no brackets repeated across signatures, and the type checker still knows the parameter is a Page.

03. Step 2: a per-request resource with yield

Rules are stateless; resources need a lifecycle. A dependency that yields runs its setup, hands the value to the handler, and runs the code after yield once the response is on its way — one open/close cycle per request. Put the cleanup in a finally: when a handler raises, the exception is thrown into the dependency at the yield point, and code after a bare yield is skipped.

Python · deps.py (continued)
def reading_session() -> Iterator[str]:
    EVENTS.append('session open')
    try:
        yield 'session'
    finally:
        EVENTS.append('session close')


Session = Annotated[str, Depends(reading_session)]
Python · main.py
from fastapi import FastAPI

from deps import PageParams, Session

app = FastAPI()

TITLES = [
    'Refactoring',
    'Domain-Driven Design',
    'The Pragmatic Programmer',
]


@app.get('/titles')
def list_titles(page: PageParams, session: Session):
    window = TITLES[page.offset : page.offset + page.limit]
    return {'window': window, 'session': session}
Python · drive.py (drive the route and watch the events)
import time

from fastapi.testclient import TestClient

from deps import EVENTS
from main import app

client = TestClient(app)


def show(qs):
    EVENTS.clear()
    r = client.get('/titles' + qs)
    time.sleep(0.05)
    if r.status_code == 200:
        print(f"{qs} -> 200 window={r.json()['window']}")
    else:
        print(f"{qs} -> {r.status_code} query rejected")
    print(f"events: {EVENTS}")


show('?limit=2&offset=1')
show('?limit=500')
Expected output
?limit=2&offset=1 -> 200 window=['Domain-Driven Design', 'The Pragmatic Programmer']
events: ['page solved', 'session open', 'session close']
?limit=500 -> 422 query rejected
events: ['session open', 'session close']

Read the two event lines carefully. On the successful request the paging dependency ran, then the session opened and closed — one full cycle for that request; the next request opens a fresh one. On the rejected request, page_params never ran, yet the session still opened and closed: dependencies declared in the same signature are solved together, and the finally still runs the cleanup when a sibling parameter fails validation. This per-request cycle is exactly how a database session stays isolated between concurrent requests — one session each, closed whatever happens.

04. Step 3: once per request, thanks to the cache

What if two parameters need the same dependency — say, a handler declares PageParams twice, or a sub-dependency also wants paging? FastAPI caches each dependency’s result for the duration of one request. The page solved log line already in page_params makes the cache visible: two declarations, one solve.

Python · main.py (replace list_titles: the handler wants paging twice)
@app.get('/titles')
def list_titles(page: PageParams, again: PageParams, session: Session):
    window = TITLES[page.offset : page.offset + page.limit]
    return {'window': window, 'session': session}
Expected output (one request, paging needed twice)
?limit=2&offset=1 -> 200 window=['Domain-Driven Design', 'The Pragmatic Programmer']
events: ['page solved', 'session open', 'session close']

One page solved, not two, despite two parameters declaring it. The cache is per request, not per application: the next request solves it again. This is why an expensive shared value that should be built once — an HTTP client with a connection pool, a model loaded from disk — should not be created inside a dependency. Create it once in the application lifespan and let a small dependency return it; the final lesson does exactly that with get_index.

05. Step 4: swap a dependency in a test

Dependencies are declared in signatures, so replacing one does not mean editing the route. The application object keeps a dictionary of overrides, keyed by the original dependency function, mapping it to any callable that returns a replacement. FastAPI calls the replacement instead — this is how a route that normally talks to a database gets tested against an in-memory stand-in.

Python · test_titles.py
import pytest
from fastapi.testclient import TestClient

from deps import Page, page_params
from main import TITLES, app


@pytest.fixture()
def client():
    with TestClient(app) as test_client:
        yield test_client
    app.dependency_overrides.clear()


def test_default_page_is_ten(client):
    assert client.get('/titles').json()['window'] == TITLES


def test_override_forces_a_single_title(client):
    app.dependency_overrides[page_params] = lambda: Page(limit=1, offset=0)
    assert client.get('/titles').json()['window'] == TITLES[:1]
Terminal 1
python -m pytest test_titles.py -v
Expected output (trimmed)
test_titles.py::test_default_page_is_ten PASSED                          [ 50%]
test_titles.py::test_override_forces_a_single_title PASSED               [100%]

The first test proves the real dependency still applies. The second replaces it with a one-line lambda and the same route now pages differently — no query string, no limit parameter, nothing changed in the handler. Clearing the dictionary in the fixture’s teardown keeps later tests honest. In a real suite, the override target is usually a get_session or get_repo dependency, and the replacement hands back a fake or an in-memory store; the software testing skill develops that pattern.

06. Mistakes to avoid

07. Check your understanding

Practice check · 3 questions

Lifecycle of a dependency

Reason about what runs, when, and how often.

Q1. One request arrives whose handler and one sub-dependency both declare PageParams. How many times does page_params run for that request?
Q2. Where must the session close go so it also runs when the handler raises an error?
Q3. app.dependency_overrides[page_params] is set and not cleared. What do requests to that app get in the meantime?
Practice only: not graded, not saved, not evidence.

08. Apply it

Wire paging into the reading list you have been building:

  1. Add PageParams to GET /books and use offset and limit instead of the bare limit query parameter; keep the q filter.
  2. Write a reading_session yield dependency that appends to an events list, and a test that asserts one open/close pair per request — including a request that ends in 404.
  3. Add a test that overrides page_params to force limit=1 and asserts the response window; clear the override afterwards.

These are three of the requirements listed in the skill’s practice task.

09. Review prompt

Without looking back: what does Annotated[Page, Depends(page_params)] buy over calling page_params() by hand in each handler? Walk through the exact order of events for one request that uses both a paging dependency and a yield dependency, including what happens when validation fails. Finally, write the two lines that replace a dependency for testing, and say when the override stops applying.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check