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
On this page
- The problem: rules and resources that several routes need
- Step 1: shared rules as a dependency
- Step 2: a per-request resource with yield
- Step 3: once per request, thanks to the cache
- Step 4: swap a dependency in a test
- Mistakes to avoid
- Check your understanding
- Apply it
- Review prompt
Lessons of FastAPI Fundamentals
- From Function to Endpoint: Path Operations Concept · 15 min
- Lab: A CRUD Resource Held in Memory Lab · 30 min
- Validating Input and Shaping Output with Pydantic Worked example · 25 min
- Dependencies: Sharing Resources Without Globals Worked example · 20 min
- Routers, Settings and Application Lifespan Lab · 25 min
- Check: Trace a Request Through the App Knowledge check · 8 questions
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.
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.
def reading_session() -> Iterator[str]:
EVENTS.append('session open')
try:
yield 'session'
finally:
EVENTS.append('session close')
Session = Annotated[str, Depends(reading_session)]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}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')?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.
@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}?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.
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]python -m pytest test_titles.py -vtest_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
08. Apply it
Wire paging into the reading list you have been building:
- Add
PageParamstoGET /booksand useoffsetandlimitinstead of the barelimitquery parameter; keep theqfilter. - Write a
reading_sessionyield 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. - Add a test that overrides
page_paramsto forcelimit=1and 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.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.