D
DevPrepSystematic Prep
FASTAPI · MEDIUM CODEX

FastAPI Interview Questions — Medium

Real-world mechanisms, state management, edge cases, performance trade-offs, and practical coding.

50 Theory Questions5 Free Model Answers
THEORY QUESTIONS & SOLUTIONSShowing 5 of 50 questions
Q1Explain the ASGI lifecycle and how FastAPI fits into it.
  • ASGI defines a single callable async def app(scope, receive, send) handling HTTP/WebSocket/lifespan messages.
  • Lifespan events (@app.on_event("startup") legacy / lifespan context manager modern) initialize pools (DB, Redis, httpx clients) once per process — dependencies then reuse them.
  • Uvicorn manages the event loop; multiple worker processes each run the full lifespan. Interview depth: explain why per-request engine creation is an anti-pattern vs lifespan-held pools.

Q2How does the dependency injection cache work and when do you bust it?
  • Within ONE request, identical dependency (by callable identity + params) resolves once — Depends(get_db) in handler + sub-dependency shares the session.
  • Bust via use_cache=False on Depends when you genuinely need fresh resolution (per-item security checks in loops).
  • Global scope alternative: module-level singletons for cross-request sharing (connection pools) — DI is for per-request composition.

Q3Compare yield-dependencies with try/finally and their cleanup timing.
async def get_db():
    async with async_session() as s:
        yield s
  • Code before yield runs pre-handler; after-yield executes AFTER response completes (exit of context), enabling commit/rollback decisions based on exceptions propagated from handlers.
  • Caveat: background tasks using that dependency may outlive — FastAPI handles ordering but long tasks should open own sessions. Exception injection: raising inside post-yield wraps handler errors — understand interplay with custom exception middleware.

Q4How do class-based dependencies and security scopes work?
class RoleChecker:
    def __init__(self, *roles): self.roles = set(roles)
    def __call__(self, user: User = Depends(get_current_user)):
        if user.role not in self.roles: raise HTTPException(403)

@router.post("/admin", dependencies=[Depends(RoleChecker("admin"))])
  • Callable instances become parameterized dependencies — reusable guards.
  • OAuth2 scopes: Security(get_current_user, scopes=["items:write"]); token contains scopes; SecurityScopes dependency verifies hierarchy — maps to OpenAPI security UI.

Q5What are Pydantic validators v2 and how do model_validator modes differ?
@field_validator("email")
@classmethod
def normalize(cls, v): return v.lower()

@model_validator(mode="after")
def check_dates(self):
    if self.end < self.start: raise ValueError(...)
  • field_validator runs per-field pre/post coercion (mode="before" sees raw input).
  • model_validator "before" receives raw dict (cross-field normalization), "after" receives constructed model instance. Return values replace data — forgetting to return in before-validators silently drops fields (classic bug).

Unlock the remaining 45 FastAPI (Medium) questions

You've completed the 5 free sample questions. Get unrestricted lifetime access to every question, model answer, implementation challenge, and all 27+ technologies for a single payment.

₹399 India / $9 International · One-time settlement · Zero subscription

CROSS-DIFFICULTY NAVIGATION

Continue Preparing FastAPI

FastAPI Interview Questions (Medium) | DevPrep | DevPrep