Learn FastAPI · 6/14

Dependency Injection System

6 min read

Dependency Injection System 💉

Welcome back! Today, we're diving into one of FastAPI's most powerful and, dare I say, magical features: the Dependency Injection system. It's designed to be simple to use and incredibly effective for writing clean, reusable, and maintainable code.

1. Understanding Dependency Injection in FastAPI

What is Dependency Injection?

In programming, "Dependency Injection" (DI) is a design pattern where the things your code needs to work (its "dependencies") are provided to it, rather than your code creating them itself. Think of it like this: instead of a chef running to the store every time they need an ingredient, the ingredients are brought directly to their cooking station.

The Problem It Solves

Imagine you're building an API. Many of your endpoints will need similar functionalities:

  • Connecting to a database.
  • Authenticating a user.
  • Validating incoming data.

Without a system like dependency injection, you might find yourself writing the same setup and teardown code in every single route. This leads to code duplication, which is a nightmare to maintain. Change one thing, and you have to change it everywhere! 😱

How FastAPI Solves It

FastAPI's dependency injection system allows you to define these common pieces of logic as "dependencies." Then, you simply "declare" that your path operation functions need them. FastAPI takes care of the rest, "injecting" the results of these dependencies into your functions. This keeps your code DRY (Don't Repeat Yourself) and much more organized.

Fun Fact: The concept of Dependency Injection is not unique to FastAPI. It's a core pattern in many modern frameworks across different languages, including Angular (TypeScript) and NestJS (Node.js).


2. Creating and Using Basic Function Dependencies

The most common way to create a dependency is with a simple Python function. Let's see it in action.

Scenario: Shared Query Parameters

Imagine you have multiple endpoints that need to handle pagination using skip and limit query parameters. Instead of defining them in every function, we can create a dependency.

Step 1: Create the Dependency Function

A dependency is just a regular Python function. It can take the same parameters as a path operation function.

python
from typing import Annotated
from fastapi import Depends, FastAPI

app = FastAPI()

async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}

This function, common_parameters, takes optional query parameters and returns them as a dictionary.

Step 2: "Depend" on the Function in Your Path Operation

Now, we can use Depends to tell our path operation functions that they require this dependency.

python
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
    return commons

@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
    return commons

What's Happening Under the Hood?

When a request comes in to /items/ or /users/, FastAPI sees Depends(common_parameters). It then:

  1. Calls the common_parameters function with the request's query parameters.
  2. Takes the dictionary returned by common_parameters.
  3. Assigns that dictionary to the commons parameter in read_items or read_users.

Voilà! You've successfully shared logic between two different endpoints without repeating yourself. 🎉


3. Class-Based Dependencies for State Management

While functions are great for many use cases, sometimes you need to manage some state or have more complex, organized logic. This is where class-based dependencies shine.

When to Use a Class as a Dependency?

  • When you have related methods that should be grouped together.
  • When you need to maintain some state within the dependency for a single request.
  • When you want to take advantage of object-oriented programming principles.

Scenario: A Reusable Item Checker

Let's imagine you have a list of valid items, and you want to create a dependency that can check if a requested item exists.

python
from fastapi import Depends, FastAPI, HTTPException

app = FastAPI()

class ItemChecker:
    def __init__(self, item_id: int):
        self.item_id = item_id
        self.valid_items = {1: "Apple", 2: "Banana", 3: "Cherry"}

    def check(self):
        if self.item_id not in self.valid_items:
            raise HTTPException(status_code=404, detail="Item not found")
        return self.valid_items[self.item_id]

@app.get("/items/{item_id}")
async def get_item(item_name: Annotated[str, Depends(ItemChecker.check)]):
    return {"item_name": item_name}

Hold on, that doesn't quite work as we might intuitively think. When using a class method as a dependency, FastAPI doesn't automatically know how to instantiate the class. A better and more common approach is to make the class instance itself the dependency.

Here is the correct way to implement this:

python
from fastapi import Depends, FastAPI, HTTPException

app = FastAPI()

valid_items = {1: "Apple", 2: "Banana", 3: "Cherry"}

class ItemChecker:
    def __init__(self, item_id: int):
        self.item_id = item_id
        if item_id not in valid_items:
            raise HTTPException(status_code=404, detail="Item not found")
        self.name = valid_items[item_id]

@app.get("/items/{item_id}")
async def get_item(item: Annotated[ItemChecker, Depends()]):
    return {"item_name": item.name}

In this revised example, Depends() will use the type hint ItemChecker to know what to do. FastAPI will see that ItemChecker needs an item_id, and it will intelligently get it from the path. Then it will create an instance of ItemChecker, and that instance will be passed to your get_item function as the item argument.

Key takeaway: When you use a class as a dependency, FastAPI creates a new instance of that class for each incoming request. This is great because it means data from one request won't accidentally leak into another.


4. Global Dependencies: Applying Rules to Entire Routers

Sometimes you have a dependency that needs to be applied to a whole group of routes, or even every single route in your application. For example, you might want to enforce authentication on all endpoints under /admin.

This is where global dependencies come to the rescue!

Scenario: A Super Secret Admin Area

Let's create a simple dependency that checks for a special x-admin-token header.

Step 1: The Dependency Function

python
from fastapi import Depends, FastAPI, HTTPException, Header, APIRouter

async def verify_admin_token(x_admin_token: Annotated[str, Header()]):
    if x_admin_token != "super-secret-admin-token":
        raise HTTPException(status_code=403, detail="Admin token is missing or invalid")

Step 2: Applying the Dependency to a Router

Instead of adding Depends(verify_admin_token) to every single admin route, we can apply it to an APIRouter.

python
admin_router = APIRouter(
    prefix="/admin",
    dependencies=[Depends(verify_admin_token)]
)

@admin_router.get("/users")
async def get_admin_users():
    return {"users": ["admin1", "admin2"]}

@admin_router.get("/settings")
async def get_admin_settings():
    return {"settings": {"level": "super-user"}}

app = FastAPI()
app.include_router(admin_router)

Now, any request to an endpoint defined in admin_router (like /admin/users or /admin/settings) will first execute the verify_admin_token dependency. If the token is invalid, the request will be rejected before it even reaches the actual path operation function. How cool is that? 😎

You can even apply dependencies to the entire application when you create the FastAPI instance.

python
app = FastAPI(dependencies=[Depends(verify_admin_token)])

Now every route in your application is protected by this dependency.

Extra Reading & References 📚

Challenge

You are tasked with building a secure, multi-level product management API using FastAPI. Your goal is to leverage FastAPI's Dependency Injection system to handle pagination, data validation, and route-level authentication without duplicating code.

Your Tasks:

  1. Pagination Dependency: Create a function-based dependency named get_pagination_params. It must accept two optional query parameters: page (default 1) and size (default 10). The function should return a dictionary containing these two values.

  2. Validator Dependency: Implement a class-based dependency named ProductValidator. Its initializer (__init__) must accept a product_id from the path parameters. It should attempt to find the product in the provided mock_db. If the product_id does not exist in the database, it must raise an HTTPException with a status_code of 404 and an appropriate detail message. If the product is found, the instance should store the product's data.

  3. Authentication Dependency: Create a function-based dependency named verify_admin_secret. This function must check for a request header named X-Admin-Secret. If the header is missing or its value is not exactly 'supersecret', it must raise an HTTPException with a status_code of 403.

  4. Secure Router: Define an APIRouter instance named admin_router. Apply the verify_admin_secret dependency globally to this router so that all its endpoints are protected.

  5. Endpoint Implementation: Correctly wire the dependencies into the existing path operation functions:

    • The list_products function should use the get_pagination_params dependency.
    • The update_product function should use the ProductValidator dependency.
  6. Router Integration: Mount the admin_router to the main FastAPI application with a prefix of /admin.

Expected result

Your final code should correctly implement and integrate three types of dependencies into a FastAPI application.

  1. A function get_pagination_params(page: int = 1, size: int = 10) is defined. It returns a dictionary {"page": page, "size": size}.

  2. A class ProductValidator is defined. Its __init__ method is type-hinted to receive product_id: int. Inside the initializer, it checks if product_id is a key in mock_db. If not, it raises an HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Product not found"). If found, it assigns the product dictionary to an instance attribute, for example, self.product = mock_db[product_id].

  3. A function verify_admin_secret(x_admin_secret: Annotated[str | None, Header()] = None) is defined. It checks if x_admin_secret is not equal to 'supersecret'. If the condition is met, it raises HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin secret is invalid or missing").

  4. The admin_router is instantiated with the authentication dependency: admin_router = APIRouter(dependencies=[Depends(verify_admin_secret)]).

  5. The path operation function signatures are updated to use the correct dependencies:

    • list_products(pagination_params: Annotated[dict, Depends(get_pagination_params)])
    • update_product(product_id: int, product_validator: Annotated[ProductValidator, Depends()]) (Note: Depends(ProductValidator) or just Depends() works here)
  6. The admin_router is included in the main app: app.include_router(admin_router, prefix="/admin").

python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.