Backend Development

Mastering Dependency Injection in FastAPI: A Practical Guide for Clean Architecture

When building a small API with FastAPI, you can put most of your logic inside route handlers and everything will work fine. You can connect to a database,…

D
DevByteTechnical Author
Published
19 min read3 views
Mastering Dependency Injection in FastAPI: A Practical Guide for Clean Architecture

When building a small API with FastAPI, you can put most of your logic inside route handlers and everything will work fine. You can connect to a database, validate a request, fetch some records, and return a response without much effort.

But things start getting complicated when your application grows.

Imagine you're building an e-commerce API. You have authentication, user management, product listings, order processing, payment integration, and database operations. If every route creates its own database connection, verifies tokens independently, and initializes services directly, maintaining the application becomes difficult.

You might find yourself repeating the same code across multiple endpoints. Testing individual components becomes harder, and changing one implementation can affect several parts of the application.

This is where Dependency Injection (DI) becomes useful.

FastAPI provides a built-in dependency injection system through Depends(). It allows you to separate responsibilities, reuse common logic, manage resources, and keep your application easier to test and maintain.

In this guide, we'll explore how dependency injection works in FastAPI, how to use it in real projects, and how to structure dependencies when building an application using clean architecture principles.

We'll also look at database sessions, authentication, service classes, dependency overrides, and some common mistakes worth avoiding.

1. What Is Dependency Injection?

Dependency injection is a software design technique in which a component receives the objects or services it needs instead of creating them internally.

Let's start with a simple example.

Suppose you have a service responsible for retrieving users.

class UserService:
    def get_user(self, user_id: int):
        return {
            "id": user_id,
            "name": "Manjeet"
        }

Now, imagine that a route handler creates the service itself.

from fastapi import FastAPI

app = FastAPI()


@app.get("/users/{user_id}")
def get_user(user_id: int):
    service = UserService()
    return service.get_user(user_id)

This works perfectly well for a simple example.

However, the route is responsible for both handling the HTTP request and creating the service. If the service later requires a database repository, configuration, or another service, the route may become more complicated.

With dependency injection, we can provide the service through a separate function.

from fastapi import Depends, FastAPI

app = FastAPI()


def get_user_service():
    return UserService()


@app.get("/users/{user_id}")
def get_user(
    user_id: int,
    service: UserService = Depends(get_user_service)
):
    return service.get_user(user_id)

Now, FastAPI calls get_user_service() and passes its result into the route handler.

The route doesn't need to know how the service is created. It only needs to know that a service is available.

That separation is the main idea behind dependency injection.

Why does this matter?

In a real application, a dependency might provide:

  • A database session.

  • An authenticated user.

  • A service class.

  • Application configuration.

  • A Redis connection.

  • Permission checks.

  • A third-party API client.

Instead of manually initializing these components in every route, you define how they should be provided and let FastAPI resolve them.

2. Understanding Depends() in FastAPI

The Depends() function tells FastAPI that a parameter should be provided by a dependency.

Let's look at a basic example.

from fastapi import Depends, FastAPI

app = FastAPI()


def get_message():
    return "Hello from a dependency!"


@app.get("/message")
def read_message(message: str = Depends(get_message)):
    return {"message": message}

When someone requests /message, FastAPI calls get_message() and passes its return value to read_message().

The response looks like this:

{
  "message": "Hello from a dependency!"
}

Notice that we didn't call get_message() ourselves. We passed the function to Depends().

This distinction is important.

message: str = Depends(get_message)

Here, get_message is a function reference. FastAPI is responsible for calling it when resolving the dependency.

Dependencies can have their own dependencies

One of the most useful features of FastAPI's dependency system is that dependencies can depend on other dependencies.

For example, a user service might need a database session.

def get_database():
    return "Database connection"


def get_user_service(
    database=Depends(get_database)
):
    return {
        "database": database,
        "service": "UserService"
    }

A route can then depend on the user service:

@app.get("/users")
def list_users(
    service=Depends(get_user_service)
):
    return service

FastAPI resolves the dependency chain automatically.

The flow looks like this:

  1. A request arrives at the /users endpoint.

  2. FastAPI sees that the route requires get_user_service.

  3. The service requires get_database.

  4. FastAPI resolves the database dependency.

  5. It passes the database result to the service dependency.

  6. It passes the service result to the route handler.

This is called a dependency graph.

You don't need to manually execute every function in the graph. FastAPI handles the resolution process.

3. Using Dependency Injection for Database Sessions

Database connections are one of the most common use cases for dependency injection.

Consider an API that uses SQLAlchemy with PostgreSQL. Every request that interacts with the database needs access to a session.

Creating and closing sessions manually inside every route leads to duplicated code.

Instead, we can create a database dependency.

For this example, let's use SQLAlchemy 2.0 with a synchronous database session.

First, install the required packages:

pip install fastapi uvicorn sqlalchemy psycopg

Step 1: Configure the database

Create a file called database.py.

import os

from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker

DATABASE_URL = os.environ["DATABASE_URL"]

engine = create_engine(
    DATABASE_URL,
    pool_pre_ping=True
)

SessionLocal = sessionmaker(
    bind=engine,
    autoflush=False,
    expire_on_commit=False
)


class Base(DeclarativeBase):
    pass

The database URL should be configured through an environment variable rather than hardcoded into your source code.

For example, your development environment might contain:

export DATABASE_URL="postgresql+psycopg://user:password@localhost:5432/myapp"

Use appropriate secrets management for production deployments.

Step 2: Create the database dependency

Now, create dependencies.py.

from collections.abc import Generator
from sqlalchemy.orm import Session

from app.database import SessionLocal


def get_db() -> Generator[Session, None, None]:
    db = SessionLocal()

    try:
        yield db
    finally:
        db.close()

There is something important happening here.

Instead of returning a session directly, the function uses yield.

Before yield, the session is created. FastAPI provides it to the dependent route or service. When the dependency's cleanup phase runs, the finally block closes the session.

This helps ensure that database sessions don't remain open unnecessarily.

The exact cleanup timing depends on the dependency scope and how the dependency is used. For ordinary request-scoped database sessions, the important point is that the session should remain available while the request's database work is running and should be cleaned up afterward.

Step 3: Inject the session into a route

from fastapi import Depends, FastAPI
from sqlalchemy import text
from sqlalchemy.orm import Session

from app.dependencies import get_db

app = FastAPI()


@app.get("/health/database")
def database_health(
    db: Session = Depends(get_db)
):
    db.execute(text("SELECT 1"))

    return {
        "status": "healthy",
        "database": "connected"
    }

The route doesn't create or close the session itself.

It simply declares that it needs a Session.

FastAPI resolves the dependency, and the cleanup logic handles closing the session.

One important detail: creating a database session does not necessarily mean a database connection has already been checked out. SQLAlchemy generally acquires a connection when the session needs to execute database work.

Also, Depends(get_db) doesn't automatically manage every transaction decision. You should still decide where transactions begin, commit, and roll back.

For example, if a service performs several database writes that must succeed or fail together, transaction management should be explicit.

4. Organizing Dependencies with Clean Architecture

Dependency injection becomes especially valuable when you're working with clean architecture.

The basic idea of clean architecture is to keep business rules independent of external details such as HTTP requests, database implementations, and third-party APIs.

For example, consider an application that creates users.

A poorly organized application might contain all the logic inside a route:

@app.post("/users")
def create_user(payload: dict):
    # Validate user data.
    # Check whether the email already exists.
    # Hash the password.
    # Create the database record.
    # Commit the transaction.
    # Send a welcome email.
    # Return the response.
    ...

As the application grows, the route becomes responsible for too many things.

A cleaner structure separates these responsibilities.

One possible project structure is:

app/
├── main.py
├── api/
│   └── routes/
│       └── users.py
├── core/
│   └── config.py
├── dependencies/
│   └── common.py
├── schemas/
│   └── user.py
├── services/
│   └── user_service.py
├── repositories/
│   └── user_repository.py
└── database/
    ├── models.py
    └── session.py

This is only one possible structure. You don't need to create every directory for a small application.

The important part is separating responsibilities.

  • Routes handle HTTP requests and responses.

  • Schemas validate input and define response structures.

  • Services contain application use cases and business rules.

  • Repositories encapsulate data access when that abstraction is useful.

  • Database modules configure sessions, engines, and models.

  • Dependencies connect the components together.

Dependency injection helps assemble these components without forcing every route to know how all the underlying objects are constructed.

Building a service layer

Let's start with a simple service class.

# app/services/user_service.py

class UserService:
    def __init__(self, repository):
        self.repository = repository

    def get_user(self, user_id: int):
        return self.repository.get_by_id(user_id)

The service receives its repository through the constructor.

This is constructor injection.

The service doesn't create a repository internally, so we can provide different implementations when needed.

For example, production code could use a SQLAlchemy repository, while tests could use an in-memory implementation.

Create the dependency

# app/dependencies/common.py

from fastapi import Depends
from sqlalchemy.orm import Session

from app.dependencies.database import get_db
from app.repositories.user_repository import UserRepository
from app.services.user_service import UserService


def get_user_service(
    db: Session = Depends(get_db)
) -> UserService:
    repository = UserRepository(db)

    return UserService(repository)

This dependency creates the repository and passes it to the service.

The route doesn't need to know the construction details.

Use the service in a route

# app/api/routes/users.py

from fastapi import APIRouter, Depends, HTTPException

from app.dependencies.common import get_user_service
from app.services.user_service import UserService

router = APIRouter(prefix="/users", tags=["Users"])


@router.get("/{user_id}")
def get_user(
    user_id: int,
    service: UserService = Depends(get_user_service)
):
    user = service.get_user(user_id)

    if user is None:
        raise HTTPException(
            status_code=404,
            detail="User not found"
        )

    return user

The route is now relatively small.

It receives a service, asks for a user, and translates a missing result into an HTTP response.

This separation makes it easier to understand what each component is responsible for.

Is a repository always necessary?

No.

A repository can be useful when you need a clear boundary around database operations or want to support different data sources.

However, creating repositories for every model can introduce unnecessary abstraction in small applications.

If your service is simple and using SQLAlchemy directly is reasonable, you don't need to add another layer just because clean architecture diagrams include one.

The goal is maintainability, not the maximum number of files.

5. Injecting Configuration and Settings

Applications often need configuration such as API keys, database URLs, environment names, and feature flags.

Reading environment variables throughout the codebase can make configuration difficult to manage.

FastAPI dependencies can provide a centralized settings object.

Install Pydantic Settings:

pip install pydantic-settings

Create app/core/config.py:

from functools import lru_cache

from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    app_name: str = "My FastAPI Application"
    debug: bool = False

    database_url: str

    model_config = SettingsConfigDict(
        env_file=".env",
        extra="ignore"
    )


@lru_cache
def get_settings() -> Settings:
    return Settings()

The BaseSettings class loads values from the environment and, when configured, a .env file.

The lru_cache decorator avoids recreating the settings object every time the dependency is called.

Now, inject it into a route:

from fastapi import Depends, FastAPI

from app.core.config import Settings, get_settings

app = FastAPI()


@app.get("/info")
def app_info(
    settings: Settings = Depends(get_settings)
):
    return {
        "app_name": settings.app_name,
        "debug": settings.debug
    }

This is particularly helpful when your application has multiple environments.

You can use different environment variables for local development, staging, and production without changing the route implementation.

Be careful not to expose sensitive configuration values in API responses. Returning a public application name is fine; returning database credentials or secret keys is not.

6. Authentication and Authorization with Dependencies

Authentication is another area where dependency injection saves a lot of repetitive work.

Imagine you have several protected endpoints:

  • /profile

  • /orders

  • /settings

  • /payments

Each endpoint needs to identify the current user.

You could verify the token separately in every route, but that would duplicate code and make security changes harder to maintain.

Instead, define a dependency that extracts and validates the authenticated user.

For a real application, use a suitable token validation implementation. The following example demonstrates the dependency structure and assumes that decode_and_validate_token() verifies the token's signature, expiration, and relevant claims.

from typing import Annotated

from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/token")


def get_current_user(
    token: Annotated[str, Depends(oauth2_scheme)]
):
    payload = decode_and_validate_token(token)

    if payload is None:
        raise HTTPException(
            status_code=401,
            detail="Invalid authentication credentials",
            headers={"WWW-Authenticate": "Bearer"}
        )

    user = find_user_by_id(payload["sub"])

    if user is None:
        raise HTTPException(
            status_code=401,
            detail="User not found",
            headers={"WWW-Authenticate": "Bearer"}
        )

    return user

The functions decode_and_validate_token() and find_user_by_id() are application-specific placeholders. They need real implementations before this example can be used in production.

Now, use the dependency in a protected endpoint:

from typing import Annotated

from fastapi import Depends, FastAPI

app = FastAPI()


@app.get("/profile")
def get_profile(
    current_user: Annotated[dict, Depends(get_current_user)]
):
    return {
        "id": current_user["id"],
        "email": current_user["email"]
    }

FastAPI resolves get_current_user() before calling the route.

If authentication fails, the dependency raises an exception and the route handler doesn't execute.

Authentication versus authorization

These are related but different concepts.

Authentication answers the question: Who is making this request?

Authorization answers the question: Is this user allowed to perform this action?

For example, a user might be authenticated but still not have permission to delete another user's account.

You can create a separate dependency for role-based authorization:

from typing import Annotated

from fastapi import Depends, HTTPException


def require_admin(
    current_user: Annotated[dict, Depends(get_current_user)]
):
    if current_user.get("role") != "admin":
        raise HTTPException(
            status_code=403,
            detail="Admin access required"
        )

    return current_user

Use it wherever administrator access is required:

@app.get("/admin/dashboard")
def admin_dashboard(
    admin: Annotated[dict, Depends(require_admin)]
):
    return {
        "message": "Welcome to the admin dashboard",
        "admin_id": admin["id"]
    }

Now the route doesn't need to repeat the same role check.

For more complex applications, permissions may depend on ownership, organization membership, resource state, or other business rules. Those checks should be implemented explicitly rather than relying only on a user's role.

7. Understanding Dependency Caching

One useful feature of FastAPI's dependency system is request-level caching.

By default, when the same dependency is required multiple times within a single dependency graph, FastAPI generally reuses its result for that request.

Consider this example:

from fastapi import Depends, FastAPI

app = FastAPI()


def get_common_value():
    print("Dependency executed")
    return {"value": 100}


@app.get("/example")
def example(
    first=Depends(get_common_value),
    second=Depends(get_common_value)
):
    return {
        "first": first,
        "second": second
    }

With the default caching behavior, get_common_value() is normally executed once for the request, and both parameters receive the same returned object.

This is useful when several dependencies need the same database session or authenticated user.

However, there are a few details worth understanding:

  • Caching applies within the dependency resolution for a request, not across all requests.

  • Different dependency callables are not automatically treated as the same dependency.

  • use_cache=False can disable the normal cache behavior for a dependency declaration.

  • A dependency that has its own side effects may behave differently if executed more than once.

For example:

@app.get("/example")
def example(
    first=Depends(get_common_value),
    second=Depends(get_common_value, use_cache=False)
):
    return {
        "first": first,
        "second": second
    }

Use use_cache=False only when you actually need a fresh dependency result. Disabling caching unnecessarily can create extra database sessions, duplicate work, or unexpected behavior.

8. Class-Based Dependencies

Dependencies don't have to be ordinary functions.

FastAPI can also use classes as dependencies.

This is useful when a dependency has several parameters or when you want to group related request-processing logic.

For example, suppose an endpoint supports filtering and pagination.

from fastapi import Depends, FastAPI

app = FastAPI()


class Pagination:
    def __init__(
        self,
        skip: int = 0,
        limit: int = 20
    ):
        self.skip = max(skip, 0)
        self.limit = min(max(limit, 1), 100)


@app.get("/products")
def list_products(
    pagination: Pagination = Depends(Pagination)
):
    return {
        "skip": pagination.skip,
        "limit": pagination.limit
    }

A request such as /products?skip=20&limit=10 produces the pagination values required by the endpoint.

FastAPI inspects the class constructor, interprets its parameters, validates incoming values, and creates an instance for the dependency.

The class groups the pagination logic in one place.

You can reuse it across multiple endpoints without duplicating the same parameters.

One practical consideration: validating query parameters at the boundary is usually preferable to silently accepting arbitrary values. The example clamps the values to keep the demonstration simple, but you can also use Query constraints or Pydantic models when you want explicit validation errors.

9. Testing Dependencies with dependency_overrides

One of the biggest benefits of dependency injection appears during testing.

Suppose your production application uses PostgreSQL. You don't necessarily want every test to connect to a production database or require the full infrastructure to be available.

FastAPI provides app.dependency_overrides, a dictionary that allows you to replace a dependency with another callable.

Let's say your route uses this dependency:

def get_current_user():
    # Real authentication logic
    ...

For a test, you can replace it with a fake user.

from fastapi.testclient import TestClient

from app.main import app
from app.dependencies.auth import get_current_user


def override_get_current_user():
    return {
        "id": 1,
        "email": "test@example.com",
        "role": "admin"
    }


app.dependency_overrides[get_current_user] = (
    override_get_current_user
)

client = TestClient(app)


def test_admin_dashboard():
    response = client.get("/admin/dashboard")

    assert response.status_code == 200
    assert response.json()["admin_id"] == 1

In this test, FastAPI uses the fake user instead of running the real authentication dependency.

That means the test can focus on the endpoint's behavior rather than token generation, decoding, or database lookups.

Always clean up dependency overrides

Overrides can affect later tests if you leave them in place.

For a simple test module, you can clear them afterward:

def teardown_function():
    app.dependency_overrides.clear()

In a larger project, a pytest fixture is often a better option because it can apply the override for a specific test and restore the original state afterward.

For example:

import pytest
from fastapi.testclient import TestClient

from app.main import app
from app.dependencies.auth import get_current_user


@pytest.fixture
def client():
    app.dependency_overrides[get_current_user] = (
        override_get_current_user
    )

    with TestClient(app) as test_client:
        yield test_client

    app.dependency_overrides.clear()

This makes the setup and cleanup easier to manage.

For database tests, you can use the same technique to provide a test session or a session connected to an isolated test database.

10. Managing Resources with yield Dependencies

So far, we've used yield to manage database sessions. The same idea can be applied to other resources that need cleanup.

For example, a dependency might acquire a resource before a request and release it afterward.

from collections.abc import Generator


def get_resource() -> Generator[dict, None, None]:
    resource = {
        "connected": True
    }

    try:
        yield resource
    finally:
        resource["connected"] = False

The code before yield prepares the resource. The code after yield runs during cleanup according to the dependency's scope and execution lifecycle.

This pattern can be useful for resources such as:

  • Database sessions.

  • Temporary resources.

  • Files that need to be closed.

  • Certain client or transaction contexts.

However, don't assume that every resource should be opened and closed for every request.

For example, a long-lived connection pool is usually created at application startup and shared across requests, while individual database sessions are created for the relevant unit of work.

Understanding the difference between application-scoped resources and request-scoped resources is important when designing a production application.

A note about asynchronous dependencies

FastAPI supports both synchronous and asynchronous dependencies.

For example:

async def get_data():
    return {"message": "Async dependency"}

You can inject this dependency into an asynchronous endpoint:

from typing import Annotated

from fastapi import Depends


@app.get("/async-data")
async def read_data(
    data: Annotated[dict, Depends(get_data)]
):
    return data

For asynchronous database access, use an async-compatible database driver and session configuration. Simply changing def to async def does not make synchronous database operations non-blocking.

Likewise, avoid performing blocking operations directly inside an async endpoint. Use an appropriate async API or move blocking work into a suitable execution context.

11. Common Dependency Injection Mistakes

Dependency injection makes applications easier to organize, but there are still a few mistakes worth avoiding.

Mistake 1: Putting all business logic in dependencies

Dependencies are useful for resolving objects and handling cross-cutting concerns, but they shouldn't automatically become the place for every business operation.

For example, a dependency that checks authentication makes sense.

A dependency that performs a complicated checkout workflow, calculates discounts, charges a payment method, updates inventory, and sends notifications may be doing too much.

Keep business workflows in services or use-case classes. Use dependencies to provide those services and their required collaborators.

Mistake 2: Creating a new database engine for every request

Consider this approach:

def get_db():
    engine = create_engine(DATABASE_URL)
    SessionLocal = sessionmaker(bind=engine)

    db = SessionLocal()

    try:
        yield db
    finally:
        db.close()

This creates a new engine and connection pool whenever the dependency runs.

That is generally not the desired pattern for a typical application.

Create the engine and session factory once at the appropriate application scope, then create and close sessions as needed.

The engine manages the connection pool, while the session represents a unit of database work.

Mistake 3: Using dependencies as global mutable storage

A dependency can return an object that is reused within a request, but you shouldn't use that as a reason to store user-specific state in a global variable.

For example, storing the current user's ID in a module-level variable can cause data to leak between concurrent requests.

Keep request-specific data in the relevant dependency results, function parameters, or properly scoped context.

Mistake 4: Overengineering the dependency structure

You don't need a dependency function for every line of code.

For example, wrapping a simple constant in several layers of dependencies may make the application harder to understand rather than easier to maintain.

Use dependencies when they improve reuse, separation of concerns, resource management, or testability.

Mistake 5: Confusing dependency injection with transaction management

Injecting a database session doesn't automatically make all operations transactional in the way your business process requires.

Consider an order workflow that creates an order and reduces inventory.

If both operations must succeed or fail together, define the transaction boundary clearly.

A service or use-case layer can coordinate those operations, while the database dependency supplies the session.

Be especially careful when a workflow also involves external systems, such as payment providers. A database transaction cannot automatically roll back a payment that has already succeeded. Those workflows may need idempotency, compensating actions, or an outbox pattern.

12. Practical Guidelines for Production Applications

If you're building a FastAPI application that will be maintained by a team, a few habits can make the dependency system easier to work with.

Keep dependencies focused. A database dependency should provide a database session. An authentication dependency should identify the current user. Avoid combining unrelated responsibilities into one dependency.

Use constructor injection in services. When a service requires a repository, logger, or another service, accept it through the constructor rather than creating every collaborator internally. This makes the service easier to test.

Choose resource lifetimes carefully. Reuse application-level resources such as database engines and connection pools. Create shorter-lived resources, such as request sessions, at the appropriate scope.

Test important boundaries. Use dependency overrides to replace authentication, database access, and external integrations when testing individual endpoints.

Avoid unnecessary abstractions. A small API may only need a few dependencies and service functions. Introduce repositories and additional layers when they solve a real maintenance or testing problem.

Be careful with side effects. Dependencies can execute code before a route runs and during cleanup. Keep those side effects predictable, especially when the same dependency can appear in several places in the dependency graph.

Keep security checks explicit. Authentication and authorization are not interchangeable. Verify identity, permissions, resource ownership, and relevant token claims as required by your application.

Understand sync and async behavior. Use async-compatible libraries for non-blocking database and network operations. An async route does not make a blocking function asynchronous.

Conclusion

Dependency injection is one of the most useful features in FastAPI, especially when an application grows beyond a few simple endpoints.

Using Depends(), you can provide database sessions, configuration, authentication logic, and service objects without repeatedly constructing them inside route handlers.

When combined with a clean architecture approach, dependency injection also helps separate HTTP handling from business logic and data access. Routes become smaller, services become easier to test, and the application becomes more flexible when its requirements change.

You don't need a complicated architecture from day one. Start with a few focused dependencies, keep your business logic in the appropriate layer, and introduce additional abstractions when they provide a clear benefit.

For a small project, a database dependency and an authentication dependency may be enough. For a larger application, you can build on the same foundation with service classes, repositories, configuration providers, and test overrides.

The important thing is to use dependency injection to make your code easier to understand and maintain—not simply to add more layers.

Once you understand how FastAPI resolves dependencies and manages their lifecycle, you'll have a much stronger foundation for building testable, maintainable APIs.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘