Inject DB sessions, auth, and settings into endpoints using FastAPI's Depends() system.
Dependency Injection
from fastapi import Depends, HTTPException, status
from sqlalchemy.orm import Session
# DB session dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# Auth dependency
def get_current_user(
token: str = Depends(oauth2_scheme),
db: Session = Depends(get_db)
) -> User:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id: int = payload.get("sub")
if user_id is None:
raise credentials_exception
except JWTError:
raise credentials_exception
user = db.get(User, user_id)
if not user:
raise credentials_exception
return user
# Use in endpoint
@app.get("/me")
def me(current_user: User = Depends(get_current_user)):
return current_user