05.04

Dependency injection

skillmaxingPython with AIDependency injection
Visual lesson

Dependency injection

Included with Pro · 4:21
Lessons · 1,027 words

Most routes need the same things: a database session, the settings, the current user, maybe a rate-limit check. Without help, each route opens the session, reads the API key, looks up the user, and remembers to close everything on the way out, and one of them forgets. FastAPI's answer is Depends. A dependency is a plain function; a route declares that it wants the function's result as a parameter, and the framework calls it before the route, passes the value in, and runs any cleanup after the response is sent.

Dependencies compose: get_current_user can itself depend on get_session and on a header. They are cached within a request, so two parameters that both need the session share one. And they can be overridden in tests, which is the mechanism that makes a FastAPI app testable without a live database.

Pro

Continue reading

Pro unlocks every video lesson, the full notes and runnable code across the Python with AI course, from the language itself to agents, MCP, Langfuse and deployment.

Unlock full access to
Python with AIAI researchComplete system design
30% off with LAUNCH30ends in 7h 40m
Buy now
View all plans ·Already Pro? Sign in
124 online