Overview
Curated: · Written: · Reviewed:
FastAPI Web Services
In one line
FastAPI turns handler type hints into parsing, validation, dependency injection and OpenAPI docs, served by Starlette and Uvicorn. Reach for it for typed HTTP APIs, and be ready to say at which step each thing happens and what can block the event loop.
Key definitions
- Starlette: the ASGI layer. It owns routing, Request and Response, middleware, BackgroundTasks and lifespan.
- Pydantic: validates request input field by field and serializes responses.
- RequestValidationError: raised when a request misses the contract. It becomes a 422 and the handler is never entered.
- Depends: calls a callable, resolves its own parameters, and shares the result within one request.
- Yield dependency: setup before
yield, teardown after. Handler exceptions surface at theyield. - dependency_overrides:
app.dependency_overrides[fn] = replacementswaps a callable in tests.
Formulas and complexity
Database connections opened by the deployment, with each worker holding its own pool:
Hypothetical: 4 workers with pool size 10 open 40 connections.
How it works
- Uvicorn parses HTTP and calls the app with
scope,receiveandsend. - Middleware wraps that call. The middleware added last is outermost and sees the request first.
- Starlette matches path and method. A known path with the wrong method gives 405, an unknown path gives 404.
- FastAPI resolves path, query and body values and the
Dependsgraph, and Pydantic validates each value. - The handler runs. Its return value goes through
response_modelif declared.
When to use and when not to
| Situation | Choose | Why |
|---|---|---|
| Every call inside is awaitable (async driver, httpx.AsyncClient, async ORM) | async def | One loop serves many requests waiting on I/O |
Synchronous driver or requests | plain def | Runs in Starlette's threadpool (default 40 threads) |
| CPU-heavy work | separate process or queue | A loop or thread holds the CPU and stalls peers |
| Work that must finish after the response | a real queue | BackgroundTasks run in-process, do not retry, and die with the worker |
| Expected client error inside a handler | HTTPException | Domain errors belong in a custom exception handler |
Traps interviewers probe
- Blocking call inside
async def. Arequests.getthere stalls every route on that worker, including constant ones. Fix: declare the route or dependency asdef, or wrap the call inrun_in_threadpool. - Returning an ORM object with no
response_model. FastAPI serializes whatever attributes it can read, sopassword_hashleaks. Fix: declareresponse_model=UserOut, and keep the model's defaultextrasetting, becauseextra='allow'passes undeclared keys through. - A returned dict missing a required response field. That is a bug in your code, so the client gets a 500, not a 422. Fix: return the declared shape, or make the field optional.
- Yield dependency that commits after
yieldwith no try block. An exception skips the commit, so the row is not saved. Fix: commit explicitly in the handler path, and roll back on error. - Too many workers for the container. Each worker imports the app and holds its own memory and pool. Sixteen workers at 120 MB each is about 1.9 GiB before any request, which can OOM a 2 GiB limit while CPU stays low. Fix: size workers to the cores and the memory limit.
Interview tips
Open with: FastAPI builds a parsing, validation and injection contract from type hints, and the handler runs only after that contract passes. Then name the layers: Uvicorn serves, Starlette routes, Pydantic validates, FastAPI injects.
Expect these follow-ups:
- Why a plain
defroute still gets a threadpool, and what the 40-thread limit means under load. - Why a bad path parameter is a 422, and why a bad return value is a 500.
- How
response_modeldiffers from the return annotation at runtime. - How many dependencies run per request, and when
use_cache=Falseis right. - How to move slow report generation out of the request path: a queue and a status endpoint, not BackgroundTasks.
30-second outline:
- Name the layers and say the handler runs last.
- Trace the request: method and path, then validation (422), then handler, then serialization.
- State the async rule:
async defonly when every call awaits, otherwisedef. - Give one trap with its fix, such as a leaked field fixed by
response_model.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.