Skip to content
Tech Interview Prep
Technical interview guideNew

FastAPI Web Services

How FastAPI routes, validates, injects dependencies and serves requests on Starlette and Uvicorn, and what interviewers probe about async handlers, auth, sessions and production workers.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v2
Editorial status
Reviewed

Scope: FastAPI 0.100 or later (Pydantic v2 support), Python 3.10 or later, current Starlette and Uvicorn releases. Behaviour of response_model, Depends caching and yield dependency teardown is stated for these versions; re-check the official docs if a newer FastAPI major changes them..

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 the yield.
  • dependency_overrides: app.dependency_overrides[fn] = replacement swaps a callable in tests.

Formulas and complexity

Database connections opened by the deployment, with each worker holding its own pool:

DB connections=workers×pool size\text{DB connections} = \text{workers} \times \text{pool size}

Hypothetical: 4 workers with pool size 10 open 40 connections.

How it works

  1. Uvicorn parses HTTP and calls the app with scope, receive and send.
  2. Middleware wraps that call. The middleware added last is outermost and sees the request first.
  3. Starlette matches path and method. A known path with the wrong method gives 405, an unknown path gives 404.
  4. FastAPI resolves path, query and body values and the Depends graph, and Pydantic validates each value.
  5. The handler runs. Its return value goes through response_model if declared.
fail pass Uvicorn: HTTP to scope Middleware Starlette: path and method FastAPI: resolve Depends graph Pydantic validation 422, handler not entered Handler response_model serialization Response

When to use and when not to

SituationChooseWhy
Every call inside is awaitable (async driver, httpx.AsyncClient, async ORM)async defOne loop serves many requests waiting on I/O
Synchronous driver or requestsplain defRuns in Starlette's threadpool (default 40 threads)
CPU-heavy workseparate process or queueA loop or thread holds the CPU and stalls peers
Work that must finish after the responsea real queueBackgroundTasks run in-process, do not retry, and die with the worker
Expected client error inside a handlerHTTPExceptionDomain errors belong in a custom exception handler

Traps interviewers probe

  1. Blocking call inside async def. A requests.get there stalls every route on that worker, including constant ones. Fix: declare the route or dependency as def, or wrap the call in run_in_threadpool.
  2. Returning an ORM object with no response_model. FastAPI serializes whatever attributes it can read, so password_hash leaks. Fix: declare response_model=UserOut, and keep the model's default extra setting, because extra='allow' passes undeclared keys through.
  3. 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.
  4. Yield dependency that commits after yield with 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.
  5. 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 def route 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_model differs from the return annotation at runtime.
  • How many dependencies run per request, and when use_cache=False is right.
  • How to move slow report generation out of the request path: a queue and a status endpoint, not BackgroundTasks.

30-second outline:

  1. Name the layers and say the handler runs last.
  2. Trace the request: method and path, then validation (422), then handler, then serialization.
  3. State the async rule: async def only when every call awaits, otherwise def.
  4. 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.