Dependency injection
Dependency injection
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.
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.