Python / FastAPI Basics Interview Questions
What is the scope of a FastAPI dependency, and how do you share state across requests?
By default FastAPI dependencies are request-scoped — a new instance is created per request. For shared state (connection pools, caches, ML models) use module-level variables initialised in the lifespan context manager.
from contextlib import asynccontextmanager from fastapi import FastAPI, Depends from typing import Annotated import asyncpg # Module-level: shared across all requests db_pool: asyncpg.Pool | None = None ml_model = None @asynccontextmanager async def lifespan(app: FastAPI): global db_pool, ml_model # Create once at startup â shared by all workers in same process db_pool = await asyncpg.create_pool("postgresql://localhost/db", min_size=5) # ml_model = load_model("model.pkl") # load once yield # requests are served here await db_pool.close() app = FastAPI(lifespan=lifespan) # Request-scoped dependency â new connection per request from the pool async def get_conn(): async with db_pool.acquire() as conn: # borrows from the shared pool yield conn # returned to pool after request Conn = Annotated[asyncpg.Connection, Depends(get_conn)] @app.get("/users") async def list_users(conn: Conn): rows = await conn.fetch("SELECT id, username FROM users") return [dict(r) for r in rows] # Singleton dependency â same instance for all requests (use_cache=True, default) class AppState: def __init__(self): self.request_count = 0 # not thread-safe â example only app_state = AppState() def get_app_state() -> AppState: return app_state # same object every request @app.get("/stats") def stats(state: Annotated[AppState, Depends(get_app_state)]): state.request_count += 1 return {"total_requests": state.request_count}
More Related questions...