Python / FastAPI Basics Interview Questions
What is FastAPI's dependency injection system and how do you use it?
FastAPI has a powerful built-in dependency injection (DI) system. You declare dependencies as functions and inject them into route handlers using Depends(). FastAPI resolves the dependency tree automatically, handles async dependencies, and caches results per request.
from fastapi import FastAPI, Depends, HTTPException from typing import Annotated app = FastAPI() # Simple dependency â shared pagination logic def pagination(skip: int = 0, limit: int = 10): return {"skip": skip, "limit": limit} @app.get("/items") def list_items(pagination: Annotated[dict, Depends(pagination)]): return {"pagination": pagination} @app.get("/users") def list_users(pagination: Annotated[dict, Depends(pagination)]): return {"pagination": pagination} # Class-based dependency class DBSession: def __init__(self): self.db = "fake_db_connection" # in real code: create session def close(self): pass # close connection # Generator dependency â enables cleanup with finally def get_db(): db = DBSession() try: yield db.db # yield makes it a context-managed dependency finally: db.close() # runs after request completes, even on error @app.get("/data") def get_data(db: Annotated[str, Depends(get_db)]): return {"db": db} # Nested dependencies def verify_token(token: str) -> str: if token != "secret": raise HTTPException(status_code=401, detail="Invalid token") return token def get_current_user(token: Annotated[str, Depends(verify_token)]): return {"user": "alice", "token": token}
Benefits of DI in FastAPI: reusable logic (auth, DB sessions, pagination), easy testing (swap real dependencies for mocks), automatic parameter parsing from query/headers/cookies, and per-request caching (same dependency called once per request by default).
More Related questions...