OctogleHire
← Interview questions library

25 FastAPI interview questions

Run the FastAPI interview loop in four stages. Start with a 30-minute screen on production experience: API boundaries, data modeling, async I/O, testing, and debugging. Follow with a focused coding exercise that uses Python 3.12 or 3.13, FastAPI, Pydantic v2, SQLAlchemy 2.x, and pytest so you can see structure, error handling, and trade-offs. Add a system design interview for service boundaries, request lifecycle, background work, observability, and deployment choices. Finish with a behavioral and code-review stage: ask them to critique a small FastAPI pull request, explain risks, and discuss how they collaborate with product, frontend, SRE, and security peers.

Junior FastAPI questions

Fundamentals, learning speed and how they debug.

  1. 01You add a new POST endpoint that creates a resource and writes to PostgreSQL. How would you structure the request schema, response schema, route handler, and database call?

    Listen for: A strong answer separates Pydantic v2 input and output models, avoids returning ORM objects blindly, uses dependency injection for the database session, validates client-owned versus server-owned fields, and returns the correct status code. They should mention transaction boundaries, uniqueness errors, and tests for success and failure paths.

    Red flag: They put validation, database access, and response shaping into one large handler with no tests or error handling.

  2. 02A FastAPI endpoint works locally but returns 422 in staging. How would you debug it?

    Listen for: Look for methodical debugging: compare actual request payload, headers, content type, path and query parameters, and Pydantic validation errors. They should inspect logs without leaking secrets, reproduce with curl or HTTPX, check schema changes, and understand that 422 usually means request validation failed before the handler ran.

    Red flag: They assume FastAPI is broken or immediately disable validation to make the request pass.

  3. 03When would you make a FastAPI path operation async def versus def?

    Listen for: They should explain that async helps when awaiting non-blocking I/O such as async database drivers, HTTP clients, or queues, while CPU-heavy or blocking libraries can block the event loop. A good junior answer mentions consistency with the database stack and avoiding sync calls inside async handlers unless offloaded appropriately.

    Red flag: They say async def is always faster and should be used everywhere regardless of dependencies.

  4. 04How would you test an endpoint that depends on the current user and a database session?

    Listen for: Listen for pytest with FastAPI dependency_overrides, TestClient or HTTPX AsyncClient, isolated test data, and assertions on both status code and response body. They should know how to override authentication and database dependencies without hitting real external services, and clean up state between tests.

    Red flag: They only test by clicking through Swagger UI and do not know how to isolate dependencies.

  5. 05A client asks for a field to be optional on create but always present in responses. How would you model that?

    Listen for: They should separate request and response models rather than use one model for everything. Good signals include understanding Optional versus default values in Pydantic v2, server-side defaults, response_model behavior, and tests that verify omitted input is accepted while the response includes the computed or persisted value.

    Red flag: They use one all-optional schema for create, update, and response because it is quicker.

  6. 06How do you handle expected application errors, such as duplicate emails or missing resources, in FastAPI?

    Listen for: A strong answer uses HTTPException or registered exception handlers, maps domain errors to clear HTTP status codes, and returns consistent error shapes. They should avoid leaking internals, log enough context for debugging, and test errors explicitly. Bonus if they mention database constraint violations and idempotent client behavior.

    Red flag: They catch all exceptions and return 200 with an error message in the response body.

Mid-level FastAPI questions

Independent delivery, trade-offs and code quality.

  1. 07You inherit a FastAPI service where business logic is embedded in route functions. How would you refactor without stopping feature work?

    Listen for: Look for incremental extraction into service or use-case functions, keeping route handlers thin but not creating empty abstractions. They should preserve behavior with characterization tests, move validation to schemas where appropriate, keep transaction boundaries explicit, and plan small pull requests that reduce risk while new features continue.

    Red flag: They propose a full rewrite or a large framework-style architecture before understanding current pain points.

  2. 08A production endpoint sometimes takes several seconds but only under load. What would you check first?

    Listen for: Strong answers distinguish event-loop blocking, database contention, slow queries, connection pool exhaustion, external HTTP calls, and serialization costs. They should mention tracing with OpenTelemetry, structured logs with request IDs, database metrics, profiling, and load reproduction. They should avoid guessing and first narrow where time is spent.

    Red flag: They immediately add more Uvicorn workers without investigating the bottleneck.

  3. 09How would you design database session management for a FastAPI app using SQLAlchemy 2.x?

    Listen for: They should discuss dependency-injected sessions, one unit of work per request, commit and rollback strategy, avoiding global sessions, and matching sync or async SQLAlchemy with the server stack. Good answers mention Alembic migrations, connection pool sizing, test transactions, and not holding sessions across background tasks.

    Red flag: They use a module-level session shared across requests because it is convenient.

  4. 10What are the trade-offs of using FastAPI BackgroundTasks for sending emails, webhooks, or report generation?

    Listen for: Listen for clear limits: BackgroundTasks run in the web process after the response and are not a durable job queue. Good answers use them for short, non-critical work, but choose Celery, Dramatiq, RQ, Arq, or a cloud queue for retries, scheduling, idempotency, observability, and longer work.

    Red flag: They use BackgroundTasks for critical payment, notification, or data-processing workflows without retries or persistence.

  5. 11How would you evolve a public API endpoint without breaking existing clients?

    Listen for: A strong answer covers additive changes, explicit versioning when necessary, deprecation windows, response compatibility, schema examples, contract tests, and communication with consumers. They should understand that changing field names, nullability, enum values, or error formats can break clients even when the endpoint path stays the same.

    Red flag: They change the response model and expect clients to adjust because OpenAPI regenerated.

  6. 12You need to call three external services from one endpoint. How would you manage timeouts, retries, and failures?

    Listen for: They should mention HTTPX with explicit connect/read timeouts, bounded concurrency, retries only for safe or idempotent operations, circuit breaking or fallback where useful, and structured error mapping. Good answers avoid unbounded gather calls, propagate correlation IDs, and design partial failure behavior with product expectations.

    Red flag: They call external services with default timeouts and no failure policy.

  7. 13How do you keep FastAPI settings secure and manageable across local, staging, and production?

    Listen for: Look for pydantic-settings, environment-based configuration, secret managers, typed settings, validation at startup, and no secrets in code or logs. They should separate build-time from runtime config, handle feature flags carefully, and test configuration loading. They should understand container and Kubernetes environment patterns.

    Red flag: They commit .env files or read arbitrary environment variables throughout the codebase.

Senior FastAPI questions

Judgement, architecture and raising the team's bar.

  1. 14A FastAPI monolith is growing quickly. How would you decide whether to split it into services or keep it modular?

    Listen for: A senior answer weighs team boundaries, deployment independence, data ownership, latency, operational overhead, and domain coupling. They should prefer modularization first unless there is a clear service boundary, define contracts, plan data migration carefully, and avoid distributed transactions. They should include observability and ownership implications.

    Red flag: They recommend microservices mainly because the codebase is large.

  2. 15How would you approach authentication and authorization for a FastAPI API used by both internal tools and third-party clients?

    Listen for: Listen for separation of authentication from authorization, OAuth2/OIDC or JWT validation where appropriate, key rotation, scopes or roles, tenant boundaries, and policy checks outside route clutter. They should cover service-to-service calls, audit logging, testing permissions, and avoiding trust in client-supplied tenant or user fields.

    Red flag: They only check that a token exists and then let handlers decide access ad hoc.

  3. 16You are reviewing a FastAPI pull request that adds a large dependency graph. What concerns would you raise?

    Listen for: They should evaluate readability, hidden I/O in dependencies, request-scoped versus singleton resources, caching with use_cache, teardown behavior for yield dependencies, and testability. A strong answer recognizes dependencies are powerful but can obscure control flow, startup cost, security checks, and transaction ordering if overused.

    Red flag: They treat dependency injection as a place to put any logic because FastAPI supports it.

  4. 17A team wants to standardize all responses and errors across several FastAPI services. How would you lead that effort?

    Listen for: Look for a pragmatic shared standard: problem-detail style errors, correlation IDs, pagination conventions, consistent validation mapping, documented OpenAPI examples, and shared test helpers. They should avoid over-centralized packages that block teams, provide migration guidance, and consider backward compatibility for existing clients.

    Red flag: They create a mandatory internal framework that every service must adopt before shipping features.

  5. 18How would you design observability for a FastAPI service that handles customer-facing traffic?

    Listen for: A strong answer includes structured JSON logs, request IDs, OpenTelemetry traces, metrics around latency and errors, database and external-call spans, health and readiness endpoints, and log redaction. They should define useful service-level signals, dashboards, alerts, and runbooks, not just add a logging library.

    Red flag: They rely on print statements and only inspect logs after customers report problems.

  6. 19How would you manage migrations and deployment safety when changing a heavily used database table?

    Listen for: They should describe expand-and-contract migrations, backward-compatible code, Alembic revision review, index creation strategy, backfills outside request paths, feature flags where helpful, and rollback planning. Good answers mention coordinating application versions with schema states and avoiding long locks in production databases.

    Red flag: They deploy a breaking migration and application change together with no rollback or compatibility plan.

  7. 20How do you evaluate whether to use async SQLAlchemy, sync SQLAlchemy, or another data access approach in FastAPI?

    Listen for: Listen for workload-based reasoning, driver maturity, team familiarity, transaction complexity, testability, and operational behavior. They should know async is not automatic speed, sync can work well with proper workers and pools, and mixing blocking calls into async routes causes harm. Benchmarks should reflect real access patterns.

    Red flag: They choose async everywhere because FastAPI is async-capable, without considering database behavior or team experience.

System design FastAPI questions

Designing real systems end to end.

  1. 21Design a FastAPI service that accepts file uploads, validates metadata, stores files, and exposes processing status to clients.

    Listen for: A good design separates upload handling from processing, streams files rather than loading them fully, stores metadata transactionally, uses object storage, and returns a job or resource ID. They should discuss size limits, content validation, antivirus or scanning hooks, durable background processing, status polling or callbacks, and cleanup of failed uploads.

    Red flag: They process large files synchronously inside the request handler and keep them on the application container filesystem.

  2. 22Design a multi-tenant FastAPI API for a B2B SaaS product with tenant-scoped data and admin users.

    Listen for: Listen for explicit tenant resolution, authorization at service or repository boundaries, tenant-safe queries, database constraints where possible, and audit logging. They should reject trusting tenant IDs from request bodies, consider subdomains or token claims, discuss admin impersonation controls, and test cross-tenant access failures thoroughly.

    Red flag: They add tenant_id to models but rely on developers to remember filters in every query.

  3. 23Design a FastAPI gateway endpoint that aggregates data from several internal services for a frontend dashboard.

    Listen for: Strong answers cover bounded parallelism, timeouts, partial responses, caching, request collapsing if needed, and clear error semantics. They should propagate trace context, avoid turning the gateway into a domain dumping ground, document response contracts, and consider whether frontend composition or service-owned endpoints would be cleaner.

    Red flag: They fan out to every service on every request with no timeout, cache, or ownership model.

  4. 24Design a webhook ingestion system in FastAPI for third-party events that may be duplicated or delivered out of order.

    Listen for: They should verify signatures against the raw body, store received events durably, use idempotency keys or provider event IDs, return quickly, and process asynchronously. Good answers handle retries, ordering limits, dead-letter queues, replay tools, schema version changes, and observability without logging secrets or full sensitive payloads.

    Red flag: They process the webhook synchronously and assume each event arrives exactly once and in order.

  5. 25Design the deployment model for a FastAPI service on containers behind a load balancer.

    Listen for: Look for Uvicorn or Gunicorn plus Uvicorn workers chosen based on workload, health and readiness checks, graceful shutdown, connection pool sizing per worker, migrations as a controlled step, environment-based settings, TLS at the edge, structured logs, metrics, tracing, and safe rollout or rollback behavior.

    Red flag: They scale workers and replicas without considering database connections, shutdown behavior, or readiness.

Practical task · 2–3 hours

Build a small FastAPI order API with validation, persistence, and tests

Create a FastAPI service for managing customer orders. Implement endpoints to create an order, fetch it by ID, list orders with simple filters, and mark an order as canceled. Use Python 3.12 or 3.13, FastAPI, Pydantic v2, SQLAlchemy 2.x, Alembic, and PostgreSQL or SQLite with clear setup instructions. Include request and response models, database migrations, consistent error handling, and automated tests using pytest and HTTPX or TestClient. Add a short README explaining design choices, trade-offs, and what you would improve with more time.

How to evaluate it

  • Clear separation between API layer, validation models, persistence, and business rules.
  • Correct handling of validation, status codes, transactions, and not-found or invalid-state errors.
  • Useful automated tests that isolate state and cover success and failure paths.
  • Readable project structure, type hints, migrations, and local setup instructions.
  • Practical judgment: simple where appropriate, with explicit notes on scalability and production gaps.

Rather skip the interview loop?

Every Octogle FastAPI engineer has already passed a technical assessment, system design and a live interview with an engineer who has shipped FastAPI. Send a brief and get 3–5 scored profiles in 48 hours.