Skip to main content

FastAPI Dependency Injection (DI) VS. Depends

· 4 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

That's an excellent question that gets right to the core of FastAPI's design.

Yes, FastAPI Dependency Injection (DI) and FastAPI Depends are two different but closely related concepts. You can think of them as the system and the tool used to activate that system.

Here's a breakdown of the difference:

🛠️ Dependency Injection (DI): The System

Dependency Injection (DI) is the fundamental design pattern or system that FastAPI uses for handling components and business logic. It's an abstract concept rooted in software engineering principles, not unique to Python.

FeatureDescription
What it isA design pattern where components (dependencies) are "injected" into the consumers (route functions) rather than the consumers creating them internally.
PurposeTo achieve Inversion of Control (IoC), making code highly reusable, decoupled, and easy to test (by allowing mocks to be injected).
MechanismFastAPI inspects your route function signatures, identifies required components, resolves those components (by running their functions/callables), and injects the resulting values into the route.
Core Idea"Don't call us, we'll call you." The framework is responsible for handling setup and cleanup.

🔗 Depends(...): The Tool (The Syntax)

Depends is the special function provided by FastAPI (and its underlying library, Starlette) that explicitly tells the Dependency Injection system which component needs to be injected.

FeatureDescription
What it isA callable wrapper that serves as a marker or signal to the FastAPI framework.
SyntaxUsed as the default value in a function argument's type hint: user: User = Depends(get_current_user) or user: Annotated[User, Depends(get_current_user)].
ActionWhen FastAPI sees Depends(callable), it immediately knows it must execute that callable (the dependency function) before running the route.
ResultThe return value of the callable is the object or data that gets injected into the user variable in the route function.

Summary Analogy

Imagine building a custom car.

ConceptAnalogy
Dependency Injection (DI)The assembly line itself. It's the entire infrastructure responsible for moving parts, ensuring quality, and connecting components.
Depends(...)A work order ticket attached to a specific spot on the car. This ticket tells the assembly line exactly which part to install at that location (e.g., "Install Engine Model 3000").

The DI system uses the Depends tool to determine what actions to take. Without the Depends function, the powerful Dependency Injection system wouldn't know which function to run or what to inject.