How to Use Depends in FastAPI for Dependency Injection
In FastAPI, use
Depends to declare dependencies that your path operation functions need. It helps inject reusable components like database sessions or authentication logic automatically by passing them as function parameters.Syntax
The Depends function is used as a parameter default value in your path operation functions or other dependency functions. It tells FastAPI to resolve and provide the required dependency automatically.
Depends(callable): The callable is a function or class that FastAPI will call to get the dependency.- Use it as a default value for a parameter in your endpoint or dependency function.
- FastAPI handles calling the dependency and passing its result to your function.
python
from fastapi import FastAPI, Depends app = FastAPI() def common_parameters(q: str = None): return q @app.get("/items/") async def read_items(q: str = Depends(common_parameters)): return {"q": q}
Example
This example shows how to use Depends to inject a reusable dependency that provides a fake database session. The endpoint receives the session automatically without manual creation.
python
from fastapi import FastAPI, Depends app = FastAPI() class FakeDBSession: def __init__(self): self.connected = True def get_data(self): return {"data": "This is fake data from DB"} # Dependency function async def get_db(): db = FakeDBSession() try: yield db finally: pass # Here you would close the DB connection @app.get("/items/") async def read_items(db: FakeDBSession = Depends(get_db)): return db.get_data()
Output
{"data": "This is fake data from DB"}
Common Pitfalls
- Not using
Dependsand manually calling dependency functions defeats the purpose of automatic injection. - For async dependencies, always use
async defandyieldif cleanup is needed. - For classes, use them as callables or provide a function that returns an instance.
- Forgetting to add
Dependsin the parameter default means FastAPI won't inject the dependency.
python
from fastapi import FastAPI, Depends app = FastAPI() def get_number(): return 42 # Wrong: calling dependency manually @app.get("/wrong") async def wrong(): number = get_number() # Not using Depends return {"number": number} # Right: using Depends @app.get("/right") async def right(number: int = Depends(get_number)): return {"number": number}
Quick Reference
Tips for using Depends in FastAPI:
- Use
Dependsas a default value to declare dependencies. - Dependencies can be async or sync functions or classes.
- Use
yieldin async dependencies for cleanup (like closing DB connections). - Dependencies can depend on other dependencies, creating a dependency tree.
- Use
Dependsto keep your code clean and reusable.
Key Takeaways
Use Depends to declare dependencies as function parameters for automatic injection.
Dependencies can be async functions with yield for setup and cleanup.
Always use Depends in the parameter default to enable FastAPI to inject dependencies.
Dependencies can be reused and nested for clean, modular code.
Depends helps manage resources like database sessions or authentication easily.