Interview Q&A · questions with model answers
FastAPI Interview Questions
Ordered by how often they're asked. Most-asked answers are free to read in full; members see every answer and can rate their confidence on each.
-
Most asked How do you implement OAuth2 password flow with JWT in FastAPI?
Use OAuth2PasswordBearer(tokenUrl="token") as a dependency that extracts the Bearer token, issue signed JWTs (PyJWT) at the token endpoint after verifying the password hash, and decode/verify the…
-
Most asked How do you use SQLAlchemy 2.0 async with FastAPI?
Create an async engine (create_async_engine with asyncpg), an async_sessionmaker, provide a session per request via a yield dependency, and use select() with await session.execute() or…
-
Most asked How do you run startup and shutdown logic in FastAPI?
Use the lifespan parameter with an async context manager: code before yield runs at startup (create DB pools, HTTP clients, load ML models) and code after runs at shutdown.
-
Most asked How do you add middleware and configure CORS in FastAPI?
Add middleware with app.add_middleware(...) (e.g., CORSMiddleware, GZipMiddleware, TrustedHostMiddleware) or write HTTP middleware with @app.middleware("http").
-
Most asked How do you structure a larger FastAPI project?
Split routes into APIRouter modules per domain (users, orders), included with prefixes and tags, and separate schemas (Pydantic), models (ORM), services/repositories and dependencies into their own…
-
Most asked How do you test FastAPI applications?
Use TestClient (sync, based on httpx) or httpx.AsyncClient with ASGITransport for async tests, override dependencies (DB, auth, settings) with app.dependency_overrides, and use pytest fixtures for…
-
Most asked How do you deploy FastAPI in production?
Run Uvicorn with multiple worker processes (uvicorn --workers N or Gunicorn with uvicorn.workers.UvicornWorker), behind a reverse proxy or load balancer, usually in containers, with health checks…
-
Most asked How would you improve the throughput of a FastAPI service?
Profile first, then: use async drivers end to end, avoid blocking calls in async def, reuse HTTP clients and DB pools, cache hot reads (Redis), offload heavy work to queues, optimize serialization,…
-
How do you manage configuration and secrets in FastAPI?
Use pydantic-settings BaseSettings to load typed config from environment variables and .env files, cache it with @lru_cache, and inject it via a dependency so tests can override it.
-
How do you return different status codes and response types?
Set a default with status_code=201 on the decorator, raise HTTPException for errors, inject Response to modify headers/status, or return a Response subclass (JSONResponse, StreamingResponse,…
-
How do you create reusable validated types with `Annotated` in Pydantic v2?
Combine a base type with constraints and validators using Annotated, e.g. Slug = Annotated[str, StringConstraints(pattern=r'^[a-z0-9-]+$'), AfterValidator(check_reserved)], and reuse it across…
-
How would you implement API key authentication in FastAPI?
Use APIKeyHeader(name='X-API-Key') (or APIKeyQuery/APIKeyCookie) as a dependency, look up a hashed key in the database, compare in constant time, and attach the client identity for rate limiting and…
-
How would you add rate limiting to a FastAPI service?
Use middleware or a dependency backed by Redis (e.g., slowapi, fastapi-limiter, or a custom token bucket via Lua) keyed by user, API key or IP, returning 429 with Retry-After. Also enforce limits at…
-
How do you integrate Celery (or another task queue) with FastAPI?
Define tasks in a separate worker module, enqueue them from endpoints with .delay()/.apply_async() (or an async-friendly queue like arq/Taskiq), return 202 with a job ID, and expose a status…
-
How do you add observability (logs, metrics, traces) to FastAPI?
Emit structured JSON logs with request IDs (structlog or logging + contextvars), expose Prometheus metrics (prometheus-fastapi-instrumentator), and add OpenTelemetry tracing…
-
How do you run several I/O calls concurrently inside a FastAPI endpoint?
Use asyncio.gather() or (Python 3.11+) asyncio.TaskGroup to run independent awaits concurrently, with timeouts via asyncio.timeout() and proper error handling.
-
How do you call external APIs reliably from FastAPI?
Use one shared httpx.AsyncClient (created in lifespan) with explicit timeouts and connection limits, retry idempotent calls with exponential backoff (tenacity or httpx transports), and consider…
-
How do you make POST endpoints idempotent (e.g., payments)?
Require an Idempotency-Key header, store the key with the request fingerprint and resulting response in a durable store under a unique constraint, and on retry return the stored response instead of…
-
How do you securely receive webhooks in FastAPI?
Read the raw body (await request.body()), verify the provider's HMAC signature and timestamp in constant time before parsing, respond quickly (2xx), and process asynchronously and idempotently using…
-
How do you manage database migrations in a FastAPI + SQLAlchemy project?
Use Alembic: configure env.py with your metadata (async engine if needed), autogenerate migrations from model changes, review them by hand, commit them, and run alembic upgrade head during deployment.
-
How do you implement refresh tokens and logout with JWT access tokens?
Issue short-lived access JWTs (minutes) and long-lived opaque refresh tokens stored server-side (hashed) with rotation; on refresh, invalidate the old token and issue a new pair; logout revokes the…
-
How would you implement pagination in a FastAPI endpoint?
Accept validated limit/offset (or a cursor) query parameters, apply them in the query, and return items plus metadata (total, next cursor or links). Cursor/keyset pagination scales better for large…
-
How would you version a FastAPI API?
The most common approach is URL path versioning with routers mounted under /api/v1 and /api/v2, sharing services underneath; header- or media-type-based versioning is also possible.
-
How do you build generic response envelopes with Pydantic?
Subclass BaseModel and Generic[T] to create models like Page[T] or ApiResponse[T], then parametrize them in response_model=Page[UserOut]; FastAPI generates a distinct OpenAPI schema per…
-
How do you apply a dependency to all routes in a router or the whole app?
Pass dependencies=[Depends(fn)] to APIRouter(...), include_router(...) or FastAPI(...); those dependencies run for every route but their return values aren't injected.
-
How should you implement health checks for a FastAPI service?
Expose a cheap liveness endpoint (process is up) and a readiness endpoint that verifies critical dependencies (DB, cache) with short timeouts, and configure them as Kubernetes probes or load…
-
How do you share per-request data (like request ID or tenant) across layers?
Store it in request.state for code that has the request, or in a contextvars.ContextVar set by middleware so logging and services deep in the stack can read it without passing it explicitly.
-
How do you accept form data in FastAPI?
Declare parameters with Form() (requires python-multipart), or (since FastAPI 0.113) a Pydantic model annotated with Form(); files use UploadFile or File().
-
How would you implement ETags and conditional requests in FastAPI?
Compute an ETag (hash or version) for the resource, return it in the ETag header, and if the request's If-None-Match matches, return 304 Not Modified with no body. For writes, require If-Match to…
-
How would you use MongoDB with FastAPI?
Use an async driver: PyMongo's async API (successor to Motor) or an ODM like Beanie, create the client in lifespan, and map documents to Pydantic models (handling ObjectId serialization).
-
How would you serve a machine learning model with FastAPI?
Load the model once at startup (lifespan), run inference outside the event loop (threadpool, process pool, or a dedicated inference server), validate inputs with Pydantic, and consider batching and…
-
How do you write async tests for FastAPI with httpx?
Use httpx.AsyncClient(transport=ASGITransport(app=app), base_url='http://test') in an async test (pytest-asyncio or anyio), so you can also await async DB fixtures in the same event loop.
-
How do you mock external HTTP calls in FastAPI tests?
Use respx to mock httpx requests (or a custom MockTransport), or override the dependency that provides the API client with a fake implementation.
-
How do you type-check a FastAPI codebase?
Run mypy or pyright in CI with strict settings, use Annotated dependency aliases, and the Pydantic mypy plugin, so mismatched types between layers are caught before runtime.
-
How would you implement multi-tenancy in a FastAPI SaaS?
Resolve the tenant per request (subdomain, header or token claim) in a dependency, then scope all data access by tenant: shared schema with a tenant_id column plus row-level security,…
-
How do you prevent lost updates when two clients edit the same record?
Use optimistic locking: keep a version column, require the client to send the version (or If-Match ETag), and update with WHERE id = :id AND version = :v; if no row is updated, return 409/412.
-
How do you set cookies and headers on a FastAPI response?
Declare a response: Response parameter and call response.set_cookie(...) or set response.headers[...], while still returning your data; or construct and return a Response/JSONResponse directly.
-
How do you restrict a parameter to a fixed set of values?
Annotate it with a Python Enum (often str, Enum) or Literal['asc', 'desc']; FastAPI validates the input and documents the allowed values in OpenAPI.
-
How would you add 'Login with Google' (OIDC) to a FastAPI app?
Use an OAuth/OIDC client library such as Authlib: redirect to the provider with state and PKCE, handle the callback, exchange the code for tokens, validate the ID token, then create or link a local…
-
How would you implement audit logging for sensitive actions?
Record who did what, to which resource, when and from where (user ID, action, resource ID, before/after diff, request ID, IP) in an append-only store, written in the same transaction as the change…
-
How do you achieve graceful shutdown and zero-downtime deploys with FastAPI?
On SIGTERM, Uvicorn stops accepting connections, finishes in-flight requests (bounded by --timeout-graceful-shutdown) and runs lifespan shutdown. Combine this with readiness probes and rolling…
-
How do you enable response compression in FastAPI?
Add GZipMiddleware(minimum_size=1000) or, more commonly in production, let the reverse proxy or CDN compress responses (gzip/brotli).
-
How can you speed up JSON serialization in FastAPI?
Return data validated through a lean response model, or use ORJSONResponse as the default response class for faster encoding; for very hot paths, serialize once and return a Response with…
-
How would you stream LLM responses to a browser with FastAPI?
Return a StreamingResponse (or EventSourceResponse from sse-starlette) that iterates the LLM SDK's async stream and yields Server-Sent Events, with proper headers (text/event-stream, no buffering at…
-
How do you read and validate headers and cookies in FastAPI?
Declare parameters with Header() and Cookie(); header names convert underscores to hyphens automatically (user_agent → User-Agent), and you can group them in a Pydantic model (FastAPI 0.115+).
-
How would you apply clean/hexagonal architecture in a FastAPI codebase?
Keep FastAPI in an outer 'adapters' layer (routers, schemas, dependencies), put use cases in a service layer that depends on repository/port interfaces, and implement those ports with SQLAlchemy,…
-
How would you return localized error messages from a FastAPI API?
Detect the locale from Accept-Language (or a user preference) in a dependency or middleware, translate messages with gettext/Babel catalogs, and keep stable machine-readable error codes alongside…