Skip to content
>_ StartupJobList_

Interview questions · Worked answers

FastAPI interview questions and production answers

Trace one request through validation, authenticated identity, dependency acquisition, domain work, response filtering and cleanup. Distinguish framework behavior from application-owned guarantees.

For: Backend engineers building and operating FastAPI services

Guide scope and versions

FastAPI 0.162.0 with HTTP request, dependency and response behavior scoped to current official docs. Persistence, authentication, queues, server limits and ingress policy remain application/deployment responsibilities.

Question 1 of 10

What does request validation prove, and what does it not prove?

Pydantic validation establishes that input matches a declared shape/coercion policy. It does not establish that the authenticated actor may operate on that tenant, SKU, or reservation. Derive authority from server-owned identity, then authorize scoped data.

A body supplies tenant_id="T-8" and quantity 2; the principal belongs to T-7. Ignore client tenant as authority, scope repository lookup from the principal, and authorize any requested reassignment explicitly. Keep invalid-shape handling separate from forbidden/not-found policy.

Test an invalid quantity, a valid foreign-tenant identifier, and an authorized request. The same request can be structurally valid and unauthorized.

python / FastAPI 0.162.0 + httpx 0.28.1 · Worked example
from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field


class Principal:
    def __init__(self, tenant):
        self.tenant = tenant


def current_principal():
    return Principal("T-7")


class ReserveIn(BaseModel):
    sku: str
    quantity: int = Field(gt=0, le=3)


class ReserveOut(BaseModel):
    tenant: str
    sku: str
    quantity: int


app = FastAPI()


@app.post("/reservations", response_model=ReserveOut)
def reserve(body: ReserveIn, principal: Principal = Depends(current_principal)):
    if principal.tenant != "T-7":
        raise HTTPException(status_code=403, detail="forbidden")
    return {
        "tenant": principal.tenant,
        "sku": body.sku,
        "quantity": body.quantity,
        "internal_token": "must-not-leak",
    }


with TestClient(app) as client:
    invalid = client.post(
        "/reservations", json={"sku": "SKU-9", "quantity": 0}
    )
    valid = client.post(
        "/reservations", json={"sku": "SKU-9", "quantity": 2}
    )

assert invalid.status_code == 422
assert valid.status_code == 200
assert valid.json() == {"tenant": "T-7", "sku": "SKU-9", "quantity": 2}

This body asserts structural validation rejects zero quantity and the declared response model excludes an undeclared internal field. It does not exercise the forbidden branch; the separate overrides example supplies T-8 and checks that denial. No real identity provider or external server is used.

FastAPI 0.162.0 and HTTPX 0.28.1 TestClient example; synthetic principal, request validation, and response filtering; no real identity-provider or server claim.

Follow-up: Should forbidden and missing IDs always differ?

Choose a stable disclosure policy, often a scoped lookup returning 404 for foreign and missing IDs. Validate that policy on every operation; do not rely on shape validation.

Read the source: Request body · Dependencies · Errors

↑ Back to questions

Question 2 of 10

Why declare a response model if the handler returns a dict?

A narrow response model validates and documents the public shape and filters undeclared fields. It cannot make incorrect source data safe; construct output from authorized domain data and never pass secrets for downstream serialization.

An ORM object contains tenant_secret and payment_token. Return an explicit projection matching a dedicated public schema, then assert secret fields are absent including nested data. A response validation failure is a server defect; log it safely and do not echo internal values.

Exclusion lists can drift as internal models change; an allow-listed schema is easier to review.

Follow-up: Does exclude_unset guarantee no secret exposure?

No. It controls serialization of unset fields, not whether a newly added field is safe. Use a narrow public type and test it.

Read the source: Response Model

↑ Back to questions

Question 3 of 10

Who owns a session injected by `Depends`?

A yield dependency can own request-scoped acquisition and final close. Define commit/rollback in a visible unit-of-work owner. Dependency result caching within one request is neither a transaction policy nor a cross-request cache.

Two dependencies ask for the same get_session; FastAPI normally reuses the cached result. Decide whether the service or endpoint owns commit/rollback; do not let unrelated dependencies commit partial work. Close on success and exception.

For a yield dependency, Depends(scope="function") runs its exit code after the path operation returns but before the response is sent; scope="request" keeps it alive through response transmission and closes it afterward. The default is request scope. A streaming response that still needs the dependency must keep request scope; function scope can close it before the stream iterates. Choose explicitly and test normal, error, and streaming exits.

Follow-up: When should a yield dependency use function scope instead of request scope?

Use function scope when cleanup should happen before the response is sent and the response no longer needs the resource. Use request scope for a StreamingResponse whose iterator still reads that resource. Function scope cannot outlive request scope; do not close a session before response serialization or stream iteration that uses it.

Read the source: Dependencies · Classes as dependencies · Dependencies with yield: scope and streaming responses

↑ Back to questions

Question 4 of 10

How can a test prove the route uses an injected adapter?

Override the exact dependency through app.dependency_overrides with a deterministic fake, restore overrides after the test, and assert the route contract. This exercises routing and dependency resolution but does not prove production wiring or external service behavior.

A route imports a payment singleton and CI accidentally calls the network. Inject the gateway as a dependency, override it with a fake that records the scoped reservation, and assert no network client initialized. Use a fresh app or clear overrides in finally.

With scope="function", the yield finalizer runs before response send; with scope="request", it runs after the response is sent. The default request scope is required when a stream still uses the resource. This TestClient example checks closure for an ordinary JSON response only; it does not prove streaming-lifetime behavior.

python / FastAPI 0.162.0 + httpx 0.28.1 · Worked example
from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient


closed = []


class Principal:
    def __init__(self, tenant):
        self.tenant = tenant


def principal():
    return Principal("T-7")


def resource():
    try:
        yield object()
    finally:
        closed.append(True)


app = FastAPI()


@app.get("/tenants/{tenant}/reservations/{rid}")
def get_reservation(
    tenant: str,
    rid: str,
    actor: Principal = Depends(principal),
    session=Depends(resource),
):
    if tenant != actor.tenant:
        raise HTTPException(status_code=404, detail="not found")
    return {"tenant": tenant, "id": rid}


app.dependency_overrides[principal] = lambda: Principal("T-8")
try:
    with TestClient(app) as client:
        response = client.get("/tenants/T-7/reservations/R-1")
    assert response.status_code == 404
    assert closed == [True]
finally:
    app.dependency_overrides.clear()

Uses local TestClient, an overridden synthetic identity, and a synthetic yield resource. It proves the scoped negative response and dependency finalizer for this request; it does not prove network disconnect cleanup or a real authentication provider.

FastAPI 0.162.0 and HTTPX 0.28.1 TestClient example; synthetic dependency override and yield cleanup; no real database or client-disconnect claim.

Follow-up: Can the fake prove the configured provider credential works?

No. It proves the seam is replaceable. Check startup configuration separately and keep live-provider tests outside this synthetic proof.

Read the source: Testing dependencies · Testing

↑ Back to questions

Question 5 of 10

When does synchronous code block an async FastAPI route?

Normal def path functions/dependencies run in a thread pool; async def runs on the event loop. A blocking library called directly inside async code blocks that loop. Bound thread capacity and downstream concurrency.

An async route calls a synchronous database driver before awaiting HTTP. While that call runs, unrelated tasks on the same loop cannot progress. Prefer an async driver or move the complete blocking unit to a thread boundary. Consider transaction/session thread ownership and cooperative cancellation.

CPU-heavy pure Python may still contend on the GIL; use bounded process workers or an external queue when evidence warrants it.

Follow-up: Does a thread timeout stop the underlying call?

Usually not forcibly. Bound library-level timeouts and ensure the worker can complete cleanup; cancellation of the awaiting request does not kill arbitrary thread code.

Read the source: Concurrency · Path operation functions

↑ Back to questions

Question 6 of 10

What belongs in lifespan instead of module import?

Lifespan owns application-scoped resources that need startup and shutdown, such as connection pools. Import-time side effects can run in test tools and before worker processes fork, obscuring ownership.

Create a pool in an async lifespan context and close it in finally. Each worker process generally owns its pool; budget aggregate connections. Import-time pools can be inherited across fork or shared unexpectedly across tests.

Keep migrations and one-time work out of per-worker startup unless coordinated; multiple workers can start together.

Follow-up: Does lifespan run once for all workers?

Typically each worker application process runs its own lifespan. Coordinate global jobs separately.

Read the source: Lifespan

↑ Back to questions

Question 7 of 10

Are `BackgroundTasks` durable jobs?

No. They run in the same application process after the response. A crash or shutdown can lose work; lengthy/CPU-heavy work occupies worker resources. Use for small best-effort work, and a durable queue/outbox for required delivery.

Reservation commits, endpoint returns 201, then process is killed before email task starts. The reservation may be committed; the email is not guaranteed. Persist an outbox row in the transaction and publish idempotently with retry. Return a contract that distinguishes committed reservation state from notification state.

A background-task exception cannot undo the already-sent response or database commit.

Follow-up: Would awaiting email solve durability?

It couples response latency to provider availability and still cannot make DB commit plus external send atomic. Use an outbox if delivery is required.

Read the source: Background Tasks

↑ Back to questions

Question 8 of 10

What should happen when a client disconnects during a stream?

The stream generator should release upstream resources in finally, stop bounded work, and propagate cancellation where supported. Avoid holding transactions while a slow client receives bytes unless that cost is intentional.

A generator pages a remote API and yields SSE; disconnect arrives after page two. Close the upstream response/client, stop fetching, and do not claim the client saw the last event. Use event IDs/cursors and idempotent consumers for reconnect behavior.

Test normal completion, exception, and early close; resource cleanup depends on generator and dependency lifetime configuration.

Follow-up: Can reconnect resume automatically?

Only if the protocol and source define a cursor and replay semantics. An ordinary generator has no durable position.

Read the source: StreamingResponse · Yield dependencies

↑ Back to questions

Question 9 of 10

Where should request and concurrency limits live?

Enforce each limit at the layer that owns the resource: ingress for body bytes/connections, app for authenticated tenant quotas and fanout, client for downstream deadlines, and worker pool for queued work.

A request accepts 100,000 SKUs and creates one HTTP task per ID; a 30-second client timeout does not bound body parsing, task count, sockets, or total work. Validate list size, bound concurrency with a semaphore/worker pool, impose overall and per-call deadlines, and cancel remaining calls on failure.

Define partial-side-effect and retry policy. A timeout can occur after a downstream operation succeeded but before its response arrived.

Follow-up: Who should return 413 or 429?

Reject at the earliest layer with the needed context: ingress for byte limits, app for tenant quotas, downstream adapter for provider throttling. Document retry only when safe.

Read the source: Request files · Errors

↑ Back to questions

Question 10 of 10

How should service exceptions become HTTP responses?

Map known domain outcomes to stable status and response models at the route boundary. Keep unexpected errors as 500 with a correlation ID and sanitized internal log; never expose traceback, SQL, tokens, or provider bodies.

Returning {"ok":false} with status 200 for ReservationConflict makes retries and metrics treat failure as success. Map known conflict to 409, not found to the chosen scoped policy, and unexpected exceptions to 500. Do not serialize untrusted provider exception text.

Use a stable public error code while preserving the internal exception chain for diagnosis.

Follow-up: Should raw provider detail be returned for debugging?

No. Log sanitized class/correlation context internally; return a stable safe public message.

Read the source: Handling errors · Custom responses

↑ Back to questions

Salary context

Advertised salaries for these skills

These are Hacker News job posts that mention these technologies, not employee earnings or a measure of what a skill adds to pay. The amounts summarize annualized advertised minimums in approximate USD. Groups can overlap and differ in roles, locations and dates.

FastAPI posts

55 posts · 55 usable advertised salary amounts

2024-09-04 to 2026-11-09

$150,000

Median advertised minimum, approximate USD/year

Middle 50%: $114,541–$160,000

Explore FastAPI salaries → Browse matching job posts →
Currency and calculation basis

Approximate USD using ECB daily reference rates as of 2026-10-30. Original currencies and offer ranges remain on the source listings. These figures cover posts tagged FastAPI, rather than every job in the broader technology family.

↑ Back to questions

Keep exploring