Depends() - the core concept
Corefrom fastapi import Depends, HTTPException, Query
# Simple dependency function
def get_query_params(
skip: int = 0,
limit: int = 20
) -> dict:
return {"skip": skip, "limit": limit}
@app.get("/items")
async def list_items(
params: dict = Depends(get_query_params)
):
return params # {"skip": 0, "limit": 20}
# Class-based dependency (stateful)
class Pagination:
def __init__(self, page: int = 1, per_page: int = Query(20, le=100)):
self.page = page
self.per_page = per_page
self.skip = (page - 1) * per_page
@app.get("/posts")
async def list_posts(
pagination: Pagination = Depends(Pagination)
):
return {"skip": pagination.skip, "per_page": pagination.per_page}
# Chained dependencies
async def get_db():
async with SessionLocal() as session:
yield session
async def get_current_user(
token: str = Depends(oauth2_scheme),
db = Depends(get_db) # deps can depend on deps
):
return await validate_token(token, db)Tip: Within one request, a dependency used in several places runs once and its result is shared - if the route and get_current_user both depend on get_db, they get the same session.