Depends()
is one of the most powerful features in FastAPI, but many developers only use it for basic use cases. In this blog, I’ll share 5 helpful tips with Depends()
that can make your code cleaner, more reusable, and easier to test.
So, what is Depends in FastAPI?
In simple terms, Depends is how FastAPI automatically “injects” a function or object into your route, without you having to manually call it.
This is called Dependency Injection – a design pattern that allows you to pass shared components (like user info, database connections, params validation, etc.) into your code in a clean and reusable way.
Sounds technical? Don’t worry — just think of it like this: instead of repeating the same user authentication logic in every API endpoint, you write it once, and then use Depends to “plug it in” wherever you need.
Real-World Use Cases of Depends
• Authentication: Extracting user info from a token.
• Database Sessions: Sharing a DB connection without repeating code.
• Reusable Logic: Filtering, pagination, permission checks, configuration, etc.
Now let’s get started!
1. Use Depends with Default Parameters (And How to Override)
You can add default values to dependencies just like function parameters.
from fastapi import FastAPI, Depends
app = FastAPI()
def get_user(role: str = "guest"):
return {"role": role}
@app.get("/me")
def read_me(user = Depends(get_user)):
return user
When you call /me
, the result will be:
{"role": "guest"}
But you can also override the role
by passing it from another dependency:
def get_admin_role():
return "admin"
def get_user(role: str = Depends(get_admin_role)):
return {"role": role}
@app.get("/admin")
def read_admin(user = Depends(get_user)):
return user
Now when you call /admin
, the result will be:
{"role": "admin"}
Why useful?
You can reuse the get_user()
function and change the role depending on the route or permission level.
2. Reuse Dependencies Across Endpoints
You can create a dependency once and reuse it in multiple routes.
from fastapi import Header, HTTPException, Depends
def get_token_header(x_token: str = Header(...)):
if x_token != "my-secret-token":
raise HTTPException(status_code=400, detail="Invalid token")
@app.get("/secure-data", dependencies=[Depends(get_token_header)])
def secure_data():
return {"message": "This is secure"}
Why useful?
Avoid repeating logic like token checks in every endpoint.
3. Use Class as Dependency
You can use classes with __call__
to manage shared logic or state.
class VerifyToken:
def __init__(self, token_prefix: str):
self.token_prefix = token_prefix
def __call__(self, x_token: str = Header(...)):
if not x_token.startswith(self.token_prefix):
raise HTTPException(status_code=403, detail="Invalid token")
verify_token = VerifyToken(token_prefix="Bearer")
@app.get("/items", dependencies=[Depends(verify_token)])
def get_items():
return {"items": [1, 2, 3]}
Why useful?
Use classes when you want to pass parameters to your dependency logic.
4. Depends in Depends
You can nest dependencies. FastAPI will resolve everything in the right order.
def get_db():
db = "fake_database_connection"
return db
def get_user(db=Depends(get_db)):
return {"user_id": 1, "db": db}
@app.get("/profile")
def get_profile(user=Depends(get_user)):
return user
Why useful?
Great for composing logic like get_user → get_db → settings
, etc.
5. Use Override Depends for Testing
When writing tests, you can override dependencies.
from fastapi.testclient import TestClient
def fake_get_user():
return {"user_id": 999, "role": "test"}
app.dependency_overrides[get_user] = fake_get_user
client = TestClient(app)
def test_profile():
response = client.get("/profile")
assert response.json()["user_id"] == 999
Why useful?
You can isolate and control what each endpoint returns in unit tests.
✅ Summary
Tip | Description |
---|---|
1 | Use defaults inside dependency and override it |
2 | Reuse shared logic with dependencies=[...] |
3 | Use classes for dynamic dependency |
4 | Nest Depends() inside other Depends() |
5 | Override for testing |
Thanks for reading!
If you find these tips helpful, try applying them in your next FastAPI project.