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.

Read
14 min
Practice MCQs
25
Interview Q&A
25
Edition
v1
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

FastAPI interviews are less about decorators than about where work happens: which layer parses a request, which layer rejects it, what runs on the event loop, and what is still running after the response leaves. A candidate who can trace one request through Uvicorn, Starlette, Pydantic and the handler, and name the status code at each exit, answers most follow-ups before they are asked. This guide builds that trace first, then the rules that follow from it.

The model to carry: FastAPI turns a Python function signature into a parsing, validation, injection and documentation contract. The handler runs only after that contract is satisfied.

Why FastAPI exists and what it is built on

FastAPI sits on two libraries and adds a third concern. Name all three early in an interview.

  • Starlette is the ASGI web layer. It owns routing, the Request and Response objects, middleware, background tasks and the lifespan protocol. FastAPI is a subclass of Starlette's application class.
  • Pydantic owns validation and serialization. A parameter annotated with a BaseModel subclass is parsed from JSON and checked field by field. Responses are serialized through the same machinery.
  • OpenAPI generation is FastAPI's own layer. It reads the same type hints, emits JSON Schema for every model, and backs the interactive /docs page.

One annotation drives three outcomes: runtime validation, serialization and the published contract. When an annotation is wrong, all three are wrong together (see the OpenAPI section below).

Uvicorn is not part of FastAPI. It is an ASGI server that speaks HTTP and calls the application. FastAPI and Starlette run inside that call.

Interviewers probe whether you can say which layer rejects a bad path parameter (FastAPI's validation, via Pydantic) and which layer matches the path template (Starlette). A weak answer says FastAPI handles everything.

Request lifecycle

Follow GET /items/5?q=abc through the stack:

  1. Uvicorn accepts the connection, parses HTTP, and builds an ASGI scope dict with method, path and headers.
  2. Uvicorn calls the application with scope, receive and send. Middleware wraps this call in the order it was added.
  3. Starlette's router matches the template /items/{item_id} and the method GET. A path that matches with the wrong method returns 405, not 404.
  4. FastAPI resolves parameters: item_id from the path, q from the query string, and any Depends callables, which are run.
  5. Pydantic validates each extracted value against its annotation. Failures are collected into a RequestValidationError.
  6. The handler runs. Its return value is serialized, through response_model if one is declared.

Worked trace, with a hypothetical handler def read_item(item_id: int, q: str | None = None) and a hypothetical in-memory dict db = {5: {...}}:

# GET /items/5?q=abc
#   step 5 passes, handler runs, returns db[5], serialized, 200
#
# GET /items/five
#   step 5 fails: item_id is not an int
#   FastAPI raises RequestValidationError -> 422
#   the handler body is never entered
#
# GET /items/7   (db has no key 7; handler does return db[item_id])
#   KeyError is raised inside step 6 and nothing catches it -> 500

State the rule precisely. A 422 means the request did not match the contract, and the handler was never entered. The response body is structured and lists the failing location and error type. A 500 means the handler, or something it called, raised an exception that nothing caught. The body is generic, because the framework cannot tell what the exception means. A failed response validation is also a 500, because the defect is in the app, not the caller.

Weak answer: validation errors are 400s. FastAPI returns 422 for request validation.

Parameters and Pydantic models

FastAPI infers the source of each parameter from its name and type:

  • A name that appears in the path template is a path parameter.
  • A scalar type that is not in the path is a query parameter.
  • A parameter whose type is a BaseModel subclass is a request body.
  • A parameter with no default is required. A default of None makes it optional.

Query, Path, Body and Header override inference when the default rule picks the wrong source. A list read from the query string needs Query(...). A scalar that must come from the body needs Body(...). State the override when the source matters for the contract.

response_model is the boundary people get wrong. Returning an ORM object through a UserOut model that has no password_hash field drops that field, even though the ORM object carries it. Returning the raw ORM object without response_model serializes whatever attributes FastAPI can read from it, which is how secrets leak.

The distinction interviewers probe: input validation rejects a bad request with 422. Output validation checks what the app returned. A missing field in returned data is a bug in your code, so it surfaces as a 500.

Weak answer: response_model is for documentation. It also filters and validates the response at runtime.

Dependency injection with Depends

Depends(fn) calls fn, resolves its own parameters the same way, and passes the result in. Four behaviours matter:

  • Sub-dependencies form a graph. FastAPI resolves the whole tree before the handler runs.
  • Per-request caching. If several parameters in one request depend on the same callable, it runs once and the result is shared. Depends(fn, use_cache=False) opts out.
  • Class-based dependencies. A class is a callable whose __init__ parameters are resolved like a function's. Depends() with no argument uses the annotated class.
  • Yield dependencies run setup before yield and teardown after. A session opened in a yield dependency stays open while the request is handled, and exceptions raised in the handler reach the code after yield. The exact point at which teardown runs relative to the response changed across FastAPI releases, so check the release notes for the version you cite before stating it.

Dependency overrides are the test seam: app.dependency_overrides[get_db] = get_test_db swaps the callable everywhere it is depended on (see Testing).

Interviewers probe per-request caching. If a dependency is used by two sub-dependencies, how many times does it run? Once per request, unless use_cache=False.

Async def versus def

The event loop runs one coroutine at a time. A coroutine gives up control only at an await. An async def handler is therefore a promise that nothing in it blocks.

A blocking call inside async def stops every other request on that worker. Hypothetical figures: a handler that calls time.sleep(0.2) inside async def serves at most about 5 requests per second per worker, however many connections are open, because the loop cannot run anything during the sleep. The same handler written as plain def runs in Starlette's threadpool, whose default limit is 40 threads. Forty concurrent sleeps then finish in about 200 ms, not 8 seconds.

The rule: use async def only when every call inside it is awaitable, such as an async driver, httpx.AsyncClient or an async ORM. Use plain def for synchronous drivers such as a classic SQLAlchemy session or requests. CPU-bound work blocks in either form, so move it to a process pool or a separate worker.

Weak answer: async is faster. Strong answer: async lets one thread wait on many I/O operations, but only if nothing in the coroutine blocks. One blocking call serializes the whole worker.

Middleware, exception handlers, background tasks and lifecycle

Middleware wraps the whole application. In Starlette, the middleware added last is the outermost layer: it sees the request first and the response last. Expect a question on ordering.

HTTPException is an exception FastAPI turns into a response with the given status code and detail. @app.exception_handler(MyError) maps your own exception class to a response. Use HTTPException for expected client errors raised inside handlers. Use a custom handler for domain errors, so internal class names do not leak into responses.

BackgroundTasks run after the response is sent, in the same process. They are not a queue. They do not retry, they are lost if the worker dies mid-task, and they occupy the worker while they run. Work that must complete belongs in a real queue.

Lifespan events create shared resources once per process. A connection pool opened at startup and closed at shutdown is shared by all requests. Opening a pool per request is the failure this pattern exists to prevent.

Weak answer: background tasks run in a separate worker. They run in the same process, after the response.

Authentication, database sessions and production

The OAuth2 password flow uses OAuth2PasswordBearer(tokenUrl=...) as a dependency. It reads the Authorization: Bearer <token> header and returns the token string. When the header is absent it responds 401. Your code still validates the token.

JWT validation has three checks to name. The signature must verify against the expected key and an explicitly pinned algorithm list, and none is never accepted. The exp claim must be in the future. aud and iss should be checked when tokens cross services. Libraries differ in defaults: PyJWT checks exp when the claim is present, but confirm the options in the library and version you use rather than assuming.

Database sessions follow the yield pattern from the dependencies section: one session per request, opened on entry, committed or rolled back according to the handler's outcome, and closed afterwards. A session shared across requests is a concurrency bug.

Production runs Uvicorn with workers, or Gunicorn supervising Uvicorn workers. Each worker is a separate process with its own memory, event loop and connection pool. Hypothetical figures: 4 workers each holding a pool of 10 connections open 40 connections to the database. Adding workers adds memory per process and multiplies pools, and past the core count it adds little throughput for CPU-bound work. For I/O-bound async work, a few workers often suffice.

Weak answer: set workers to 100 for speed. Each worker multiplies memory and database connections.

Testing and OpenAPI

TestClient runs the ASGI app in-process, with no network. Tests therefore go through the same routing and validation as production. Override the database and auth dependencies with app.dependency_overrides to test handlers without a live database or a real token issuer.

The OpenAPI schema is generated from the same annotations used for validation. If a return annotation says int and the handler returns a string, the schema advertises an integer, response validation fails with a 500, and the published contract is wrong. If a parameter is annotated str when the code needs a number, the schema tells clients any string is acceptable, and the 422 path becomes the only defence. When an annotation is wrong, validation, serialization and documentation disagree together. The symptom usually appears first as an unexpected 500 or as a wrong schema in /docs.

Likely follow-ups: why a plain def handler still gets a threadpool, how response_model differs from the return annotation at runtime, how many database connections a 4-worker deployment with pool size 10 opens, and how to move a slow report generation out of the request path (a queue and a status endpoint, not a background task).

Feedback on this overview