Deepen your FastAPI vocabulary — lifespan context managers, test overrides, background tasks, and response shaping.
0 / 5 completed
1 / 5
At standup, a backend developer explains the lifespan context manager in FastAPI. Which description is correct?
The lifespan parameter (FastAPI 0.93+) accepts an @asynccontextmanager function. Code before yield runs on application startup (e.g. connecting to a database, loading ML models); code after yield runs on shutdown (e.g. closing connections). It replaces the deprecated @app.on_event("startup") decorator with a cleaner, testable pattern.
2 / 5
In a PR review, a teammate uses dependency overrides in tests. What is the correct explanation?
app.dependency_overrides is a dict on the FastAPI app instance. Setting app.dependency_overrides[get_db] = get_test_db tells FastAPI to inject get_test_db wherever get_db is declared as a dependency, for the lifetime of the TestClient. It works with both sync and async dependencies and requires no patching of production code.
3 / 5
An incident involves a slow endpoint that is blocking the event loop. A teammate suggests BackgroundTasks. What is correct?
BackgroundTasks run the added functions after the HTTP response has been sent to the client. They run in the same event loop thread (async functions) or in a thread pool (sync functions). They are suitable for lightweight I/O work like sending emails or writing audit logs. For CPU-bound or long-running work, use a proper task queue like Celery, ARQ, or Dramatiq.
4 / 5
In a design review, the team discusses response_model_exclude and response_model_include. What is correct?
response_model_exclude and response_model_include are per-endpoint parameters (on @app.get, @app.post, etc.) that filter the serialised response without modifying the Pydantic model itself. exclude blacklists fields; include whitelists fields. Both accept a set of field names or a nested dict for nested model filtering.
5 / 5
In a code review, a developer creates a custom Request class in FastAPI. What is the correct approach?
FastAPI (via Starlette) supports custom Request classes. Subclass fastapi.Request, add your properties (e.g. lazy-parse a JWT into a tenant ID), then pass request_class=MyRequest to the FastAPI() constructor. Type-annotate path operation parameters with request: MyRequest to get your custom class injected. This avoids boilerplate dependency functions for request-level concerns.