Dependency injection is a design pattern where components receive their dependencies from the framework rather than creating them internally. This separates business logic from infrastructure concerns such as databases, configuration, or authentication. The result is code that is easier to test, reason about, and evolve.
Depends() Explained Properly
In FastAPI, Depends() declares that a function requires an external dependency to execute. FastAPI resolves these dependencies automatically at request time, managing their creation, execution order, and cleanup. This mechanism is explicit, type-safe, and tightly integrated with request handling.
from fastapi import Depends, FastAPIapp =FastAPI()defget_config():return{"env":"dev"}@app.get("/info")defread_info(config:dict=Depends(get_config)):return config
Reusable Logic for Authentication, Databases, and Configuration
Dependencies allow shared logic to be defined once and reused across multiple endpoints. Common use cases include authentication checks, database session management, and configuration loading. This avoids duplication and ensures consistent behavior across the application.
Dependency Chains and Overrides
FastAPI supports dependency chains, where one dependency depends on another. This enables complex composition while maintaining clarity and control. Dependencies can also be overridden, which is especially useful for testing and environment-specific behavior.