FastAPI
Dependency Injection
Share logic via Depends and yield-based dependencies.
By EZ4Code Team
dependency-injectiondepends
Code
from fastapi import FastAPI, Depends, Header, HTTPException
app = FastAPI()
def common_params(q: str | None = None, skip: int = 0, limit: int = 10):
return {"q": q, "skip": skip, "limit": limit}
def verify_token(x_token: str = Header()):
if x_token != "secret":
raise HTTPException(status_code=400, detail="bad token")
return x_token
def get_db():
db = open_db()
try:
yield db
finally:
db.close()
@app.get("/items")
def list_items(commons: dict = Depends(common_params), token: str = Depends(verify_token)):
return commons
@app.get("/users")
def list_users(db = Depends(get_db)):
return db.query("users")Explanation
Dependencies declared with Depends are resolved by FastAPI and injected into the handler, which encourages reusable logic for params, auth, and resources. A generator dependency with yield runs setup before and cleanup after the request. Sub-deps and caching make complex wiring concise.
More FastAPI Snippets
Path Parameters
Capture typed path segments with validation.
Query Parameters
Parse query strings with defaults and validation.
Pydantic Request Body
Validate JSON bodies with Pydantic models.
Response Model
Shape and filter responses with response_model.
JWT Auth
Issue and verify JSON Web Tokens with OAuth2.
Async and Await
Define async handlers and run blocking work in a thread.