Depends() function — making your API endpoints clean, composable, and side-effect-free.
What is a Dependency?
A dependency is any external object that another object needs to do its job. Common examples:- A database connection or session
- A repository (data access layer)
- A logger
- An email service
- A configuration object
- An authentication/authorisation service
Without Dependency Injection
When a class creates its own dependencies internally, it becomes tightly coupled to that specific implementation:- You cannot test
Carwithout also instantiatingEngine. - Replacing
Enginewith aMockEngineorElectricEnginerequires modifyingCar’s source code. - Behaviour is hidden — the caller cannot control what
Caruses internally.
With Dependency Injection
The dependency is supplied from outside — the object receives it rather than creating it:Car only uses the engine — it has no knowledge of how to create one. You can pass any compatible object, including a test double.
Real-World Example: Repository & Service
Without DI — Tightly Coupled
With DI — Loosely Coupled
StudentService:
Benefits of Dependency Injection
Types of Dependency Injection
Constructor Injection (Most Common)
Setter Injection
Method Injection
FastAPI’s Dependency Injection
FastAPI automates dependency injection for your API routes using theDepends() function:
get_repository() automatically before executing get_students, and injects the result as the repo parameter.