Python / FastAPI Basics Interview Questions
How do you use class-based dependencies and sub-dependencies in FastAPI?
Dependencies can be classes with a __call__ method, enabling stateful or configurable dependencies. Sub-dependencies are automatically resolved — FastAPI builds the full dependency tree per request.
from fastapi import FastAPI, Depends, HTTPException from typing import Annotated app = FastAPI() # Class-based dependency â holds configuration class PaginationParams: def __init__( self, skip: int = 0, limit: int = 10, max_limit: int = 100, ): if limit > max_limit: raise HTTPException(400, f"limit cannot exceed {max_limit}") self.skip = skip self.limit = limit # Sub-dependency tree: # get_current_user â verify_token â oauth2_scheme def verify_token(token: str = Depends(oauth2_scheme)) -> dict: if token != "valid": raise HTTPException(401, "Bad token") return {"username": "alice", "role": "admin"} def get_current_user( payload: dict = Depends(verify_token), ) -> dict: return {"username": payload["username"]} Pagination = Annotated[PaginationParams, Depends(PaginationParams)] CurrentUser = Annotated[dict, Depends(get_current_user)] @app.get("/items") def list_items(page: Pagination, user: CurrentUser): return { "user": user["username"], "skip": page.skip, "limit": page.limit, } # Dependency with use_cache=False â new instance per call @app.get("/no-cache") def no_cache( a: Annotated[PaginationParams, Depends(PaginationParams, use_cache=False)], b: Annotated[PaginationParams, Depends(PaginationParams, use_cache=False)], ): # a and b are separate instances (default: same instance per request) return {"a_skip": a.skip, "b_skip": b.skip}
More Related questions...