Dependency Injection in FastAPI
Following our lesson on Status Codes and Error Handling in Web APIs, this article explores Dependency Injection in FastAPI. This is one of FastAPI's most powerful features, allowing you to manage dependencies and reuse code in a simple and elegant way.
📚 Prerequisites
- A running FastAPI application.
- Understanding of Python functions.
🎯 Article Outline: What You'll Master
- ✅ Foundational Theory: What Dependency Injection is.
- ✅ Core Implementation: Using
Dependsto inject dependencies. - ✅ Practical Application: Creating a common dependency for database connections or authentication.
- ✅ Classes as Dependencies: Using classes as dependencies.
🧠 Section 1: The Core Concepts of Dependency Injection
Dependency Injection is a design pattern where the dependencies of a component (e.g., a function or a class) are provided to it, rather than the component creating them itself. In FastAPI, this means you can have functions that your path operation functions "depend" on. FastAPI will take care of calling these dependency functions and passing their return values to your path operation function.
💻 Section 2: Deep Dive - Implementation and Walkthrough
Let's see how to use Depends.
# main.py
from fastapi import Depends, FastAPI, Header, HTTPException
from typing import Optional
app = FastAPI()
async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
return commons
@app.get("/users/")
async def read_users(commons: dict = Depends(common_parameters)):
return commons
Step-by-Step Code Breakdown:
async def common_parameters(...): This is our dependency function. It takes some common query parameters.commons: dict = Depends(common_parameters): In our path operation functions, we useDependsto declare the dependency. FastAPI will callcommon_parametersand pass its return value as thecommonsargument.- Now, both
/items/and/users/can reuse the same pagination logic without duplicating code.
🛠️ Section 3: Classes as Dependencies
You can also use classes as dependencies. FastAPI will call the class, creating a new instance, and pass that instance to your path operation function.
# main.py (continued)
class CommonQueryParams:
def __init__(self, q: Optional[str] = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit
@app.get("/things/")
async def read_things(commons: CommonQueryParams = Depends(CommonQueryParams)):
return commons
💡 Conclusion & Key Takeaways
You've learned how to use FastAPI's powerful dependency injection system to share code and manage dependencies between your path operations.
Let's summarize the key takeaways:
- Dependency Injection is a powerful pattern for code reuse and separation of concerns.
- FastAPI's
Dependsmakes it easy to implement. - You can create dependencies that are functions or classes.
➡️ Next Steps
In the next article, "CORS (Cross-Origin Resource Sharing) in FastAPI APIs", we'll learn how to allow web applications from other domains to access our API.
Glossary
- Dependency Injection: A design pattern where a component's dependencies are provided to it.
- Depends: A FastAPI utility for declaring dependencies.