Careeroza
Class-based & Global Dependencies
Classes as Dependencies
Example
Any callable works. A class gives you typed attributes:
from typing import Annotated
from fastapi import Depends, FastAPI
class Filters:
def __init__(self, q: str | None = None, level: str = "basic"):
self.q = q
self.level = level
app = FastAPI()
@app.get("/search")
def search(f: Annotated[Filters, Depends()]):
return {"q": f.q, "level": f.level}Requests and responses
GET /search?q=joins&level=medium
→ 200 {"q": "joins", "level": "medium"}Dependencies for a Whole App or Router
Example
Dependencies listed on the app (or a router) run for every endpoint, e.g. an API-key check:
from fastapi import Depends, FastAPI, Header, HTTPException
def verify_key(x_api_key: str = Header()):
if x_api_key != "secret-key":
raise HTTPException(status_code=403, detail="Invalid API key")
app = FastAPI(dependencies=[Depends(verify_key)])
@app.get("/reports")
def reports():
return {"reports": 3}Requests and responses
GET /reports
→ 200 {"reports": 3}
GET /reports
→ 403 {"detail": "Invalid API key"}