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.
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.
@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 commonsWhat's Happening Under the Hood?
When a request comes in to /items/ or /users/, FastAPI sees Depends(common_parameters). It then:
- Calls the
common_parametersfunction with the request's query parameters. - Takes the dictionary returned by
common_parameters. - Assigns that dictionary to the
commonsparameter inread_itemsorread_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.
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:
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
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.
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.
app = FastAPI(dependencies=[Depends(verify_admin_token)])Now every route in your application is protected by this dependency.
Extra Reading & References 📚
- Official FastAPI Documentation on Dependencies: https://fastapi.tiangolo.com/tutorial/dependencies/
- A Deeper Dive into Dependency Injection in FastAPI: https://www.freecodecamp.org/news/how-to-implement-dependency-injection-in-fastapi/
- Class-Based Dependencies: https://fastapi.tiangolo.com/tutorial/dependencies/classes-as-dependencies/
- Dependencies with
yieldfor setup and teardown: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/
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:
Pagination Dependency: Create a function-based dependency named
get_pagination_params. It must accept two optional query parameters:page(default1) andsize(default10). The function should return a dictionary containing these two values.Validator Dependency: Implement a class-based dependency named
ProductValidator. Its initializer (__init__) must accept aproduct_idfrom the path parameters. It should attempt to find the product in the providedmock_db. If theproduct_iddoes not exist in the database, it must raise anHTTPExceptionwith astatus_codeof404and an appropriate detail message. If the product is found, the instance should store the product's data.Authentication Dependency: Create a function-based dependency named
verify_admin_secret. This function must check for a request header namedX-Admin-Secret. If the header is missing or its value is not exactly'supersecret', it must raise anHTTPExceptionwith astatus_codeof403.Secure Router: Define an
APIRouterinstance namedadmin_router. Apply theverify_admin_secretdependency globally to this router so that all its endpoints are protected.Endpoint Implementation: Correctly wire the dependencies into the existing path operation functions:
- The
list_productsfunction should use theget_pagination_paramsdependency. - The
update_productfunction should use theProductValidatordependency.
- The
Router Integration: Mount the
admin_routerto the mainFastAPIapplication with a prefix of/admin.
Expected result
Your final code should correctly implement and integrate three types of dependencies into a FastAPI application.
A function
get_pagination_params(page: int = 1, size: int = 10)is defined. It returns a dictionary{"page": page, "size": size}.A class
ProductValidatoris defined. Its__init__method is type-hinted to receiveproduct_id: int. Inside the initializer, it checks ifproduct_idis a key inmock_db. If not, it raises anHTTPException(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].A function
verify_admin_secret(x_admin_secret: Annotated[str | None, Header()] = None)is defined. It checks ifx_admin_secretis not equal to'supersecret'. If the condition is met, it raisesHTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin secret is invalid or missing").The
admin_routeris instantiated with the authentication dependency:admin_router = APIRouter(dependencies=[Depends(verify_admin_secret)]).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 justDepends()works here)
The
admin_routeris included in the main app:app.include_router(admin_router, prefix="/admin").