Python / FastAPI 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}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
