FastAPI interview question · Most asked
Walk through what happens to a request in FastAPI, from the ASGI server to the response.
Summary
The ASGI server calls the app; Starlette's outer ServerErrorMiddleware wraps your middleware (the last added runs first), then ExceptionMiddleware applies your exception handlers; the router matches the path; FastAPI resolves dependencies (once per request by default) and validates parameters and the body with Pydantic (422 on failure); the endpoint runs (async def on the event loop, def in a thread pool); the return value is serialised through the response model; dependency exit code and background tasks run afterwards.
Longer Answer
Knowing the layers explains common surprises: an HTTPException raised in middleware becomes a 500 because it's outside the exception layer; validation errors never reach your endpoint; a blocking call in an async def endpoint stalls every request on the event loop. Exactly when dependencies with yield run their exit code relative to sending the response has changed between FastAPI versions, so check the documentation for your version.
Key Points
- ServerErrorMiddleware → your middleware → ExceptionMiddleware → router.
- Dependencies resolved and cached per request.
- Pydantic validation, 422 on failure.
- async def on the loop, def in a thread pool.
Deep dive: Request Lifecycle course: FastAPI and Starlette: Middleware, Exceptions and Dependencies
Explanation
What interviewers look for
The layer order and at least one consequence of it.
More most-asked FastAPI questions
- When should an endpoint be `async def` versus plain `def` in FastAPI?
- What is FastAPI and what makes it different from Flask or Django?
- How do `yield` dependencies work and why are they used for database sessions?
- How does FastAPI distinguish path, query and body parameters?
- How does FastAPI use Pydantic for request validation?
- What does `response_model` (or a return annotation) do in FastAPI?
- How does dependency injection with `Depends` work in FastAPI?
- How do you implement OAuth2 password flow with JWT in FastAPI?