Skip to main content
Dependency Injection is a software design pattern where an object or function receives other objects or services it depends on, rather than creating them internally. FastAPI has a extremely powerful, built-in Dependency Injection system that is simple to use and simplifies tasks like database connections, security, and authentication.

1. How Dependency Injection Works

When a request arrives, FastAPI inspects your route parameters. If it spots a parameter using Depends(dependency_function), it executes that dependency first, gets its return value, and passes (injects) that value directly into your route function.

2. Defining and Using a Simple Dependency

Let’s look at a common scenario: extracting and validating common query parameters (like pagination limits) for listing employees.

Advantages:

  • Reusability: You can reuse Depends(get_pagination_params) on any list route (e.g., /departments, /chats) across your app.
  • Auto-Documentation: Query parameters defined inside the dependency (skip and limit) are automatically documented in Swagger UI!

3. Sub-dependencies (Hierarchical Dependencies)

Dependencies can depend on other dependencies. This allows you to build complex trees of validation logic easily.

Example: Requiring a Validated Admin Header

Let’s define a dependency that extracts the API key, and another dependency that verifies the key belongs to an Administrator:

4. Key Use Cases for Dependency Injection in FastAPI

As our Employee Management System grows, we will use Dependency Injection for:
  1. Database Session Lifetime Management: Opening a database session before a query, injecting it, and automatically closing it after the request completes.
  2. Security & Authentication: Validating JWT tokens and fetching the details of the currently logged-in user.
  3. Role Validation: Ensuring the current user has the correct authorization scope (Admin, Manager, or Employee).