FastAPI Interview Questions and Answers
A complete list of 344+ FastAPI interview questions and answers, organized by topic. Click any question to jump straight to its detailed answer with code examples.
8 topics 344 questions
FastAPI Fundamentals
Async Basics
- What is async/await in Python and why does FastAPI use it?
- What is the difference between ASGI and WSGI?
- What is the Python event loop and how does FastAPI interact with it?
- What is a coroutine and how is it different from a regular function?
- When should you use `def` vs `async def` for a FastAPI route handler?
- What happens if you block the event loop in FastAPI, and how do you fix it?
- What does `asyncio.gather()` do and when would you use it in FastAPI?
- What is anyio and how does it relate to FastAPI?
- How do you call a synchronous function from an async context without blocking?
- Why use httpx instead of requests in a FastAPI application?
- What is Starlette and what does FastAPI add on top of it?
- Describe FastAPI's concurrency model end-to-end.
- What is `asyncio.create_task()` and how does it differ from `await`?
- How does FastAPI/anyio determine the size of its thread pool for sync handlers?
- What is the difference between `@app.on_event("startup")` and `lifespan`?
Request Lifecycle
- Walk through the lifecycle of a FastAPI HTTP request from socket to response.
- In what order does FastAPI execute multiple middleware?
- How does `HTTPException` work in FastAPI?
- How do you add a custom exception handler in FastAPI?
- What response does FastAPI return when request validation fails?
- In what order does FastAPI resolve dependencies, and what happens if two dependencies share a sub-dependency?
- How does FastAPI serialize the value returned from a route handler?
- Where in the request lifecycle do BackgroundTasks run?
- What is `jsonable_encoder` and when do you need it?
- How does FastAPI decide where to look for a parameter — path, query, or body?
- How do you change the default response status code in FastAPI?
- What is the difference between setting a path in `app.include_router(prefix=...)` vs the route decorator itself?
- Does FastAPI treat `/items` and `/items/` as the same route?
- When is the OpenAPI schema generated and can it be disabled?
Path Operations
- What is a "path operation" in FastAPI?
- Which HTTP methods does FastAPI support as route decorators?
- What is an `operation_id` and why does it matter?
- How do `tags` work in FastAPI route decorators?
- How do you mark a route as deprecated in FastAPI?
- How do you document response codes and descriptions in FastAPI?
- How do you declare that a route can return different response models for different status codes?
- Why does route order matter in FastAPI, and what is the common pitfall?
- How do you constrain a path parameter to a specific type in the URL pattern?
- What is `APIRouter` and why should you use it instead of `app` directly?
- How do you apply a dependency to every route in an `APIRouter`?
- What is the effect of adding a return type annotation to a FastAPI handler?
- How do you return a 204 No Content response from FastAPI?
- How do you define a WebSocket route in FastAPI?
- How do you serve static files in FastAPI?
Type Hints & FastAPI
- Why are Python type hints central to how FastAPI works?
- How do you declare an optional query parameter in FastAPI?
- What is `Annotated` and how does FastAPI use it?
- How do you restrict a parameter to a fixed set of values using an Enum?
- How do you accept a list of values from a query parameter?
- How do you read a request header in FastAPI?
- How do you read a cookie value in a FastAPI handler?
- How do you add validation constraints (min/max, regex) to a query parameter?
- How do you accept a single non-model value in the request body?
- How do you accept form data (not JSON) in FastAPI?
- How do you accept a file upload in FastAPI?
- How do you exclude `None` fields from a response in FastAPI?
- How do you type a route that can return one of two Pydantic models?
- How do you create a generic paginated response type in FastAPI?
OpenAPI & Docs
- How does FastAPI generate an OpenAPI schema automatically?
- What is the difference between Swagger UI (`/docs`) and ReDoc (`/redoc`) in FastAPI?
- How do you disable the API docs in production?
- How do you customise the generated OpenAPI schema in FastAPI?
- How do you add descriptions to OpenAPI tags?
- How do you add Bearer token authentication to Swagger UI in FastAPI?
- Which version of the OpenAPI specification does FastAPI generate by default?
- How do you add examples to the OpenAPI schema for a Pydantic model?
- How do you hide a route from the OpenAPI schema?
- What are the common strategies for API versioning in FastAPI?
- How do you document custom response headers in the OpenAPI schema?
- What are OpenAPI callbacks and when would you define them in FastAPI?
- How do you configure Swagger UI's OAuth2 settings (client ID, scopes) in FastAPI?
FastAPI Routing & Parameters
Path & Query Parameters
- How do you define and read a path parameter in FastAPI?
- How do you define a required query parameter in FastAPI?
- How do you give a query parameter a default value?
- How does FastAPI parse boolean query parameters?
- What happens if a path parameter and a query parameter have the same name?
- What is `Path()` and when should you use it instead of a bare type annotation?
- What extra control does `Query()` give you over a plain query parameter annotation?
- How do you accept a list of values for the same query parameter key?
- How do you use a different query string key than the Python parameter name?
- How do you mark a query parameter as deprecated in the OpenAPI schema?
- What numeric constraints can you apply to path and query parameters in FastAPI?
- What string constraints are available for query parameters?
- How do you hide a query parameter from the OpenAPI schema?
- When should a resource identifier be a path parameter vs a query parameter?
Request Body
- How do you declare a JSON request body in FastAPI?
- How do you make the request body optional in FastAPI?
- How does FastAPI handle nested Pydantic models in the request body?
- How do you declare multiple Pydantic models as separate body parameters?
- How do you mix a Pydantic body model with a singular body value?
- What happens when the client sends extra fields not defined in the Pydantic model?
- How do you accept a JSON array (list) as the root of the request body?
- How do you accept HTML form data instead of JSON in FastAPI?
- How do you accept a file alongside form fields in FastAPI?
- What does a FastAPI body validation error response look like?
- What Content-Type header does FastAPI expect for JSON body requests?
- How do you read the raw request body bytes in FastAPI without Pydantic parsing?
- How do you enforce a maximum request body size in FastAPI?
Response Models
- What does `response_model` do in a FastAPI route decorator?
- What is the difference between `response_model=` and a return type annotation?
- How do you omit `None` fields from a FastAPI JSON response?
- What is `response_model_exclude_unset` and when is it useful?
- How do you always exclude specific fields from the response without a separate output model?
- When should you return `JSONResponse` directly instead of a dict or Pydantic model?
- What response classes does FastAPI/Starlette provide and when do you use each?
- How do you use `ORJSONResponse` for faster JSON serialisation in FastAPI?
- How do you stream a large response in FastAPI without loading it all into memory?
- How do you issue a redirect from a FastAPI route?
- How do you include only specific fields in the response (whitelist instead of blacklist)?
- How do you add custom headers to a FastAPI response?
- How does a route return a response immediately while also scheduling a background task?
Routers & Structure
- What is `APIRouter` and why use it instead of the `app` object directly?
- What do `prefix` and `tags` do in `include_router`?
- How do you apply a dependency to every route in a router?
- How do you nest one `APIRouter` inside another?
- Can you set a default `response_model` or `status_code` at the router level?
- How do you add common error responses to every route in a router?
- What is the difference between `app.include_router()` and `app.mount()`?
- What is the recommended file structure for a large FastAPI application?
- Can `APIRouter` have its own lifespan events?
- How do you set a default response class for all routes in a router?
- How do you test an `APIRouter` independently without instantiating the full `FastAPI` app?
- How do you conditionally include a router (e.g., only in development)?
- How do you add a global `/api` prefix to all FastAPI routes?
FastAPI Pydantic & Validation
Pydantic Models
- What is Pydantic's `BaseModel` and why does FastAPI rely on it?
- How do you add metadata (description, example, constraints) to a Pydantic field?
- How do you mark a Pydantic field as required vs optional?
- What is a field alias in Pydantic and when would you use it?
- How does Pydantic model inheritance work and what are its use cases in FastAPI?
- What is `model_config` in Pydantic v2 and what can you configure with it?
- What is `from_attributes=True` (formerly `orm_mode`) and why is it needed?
- How do you add a computed (read-only) field to a Pydantic model?
- What is `model_validate()` and how does it differ from calling the constructor?
- What does `model_dump()` return and what options does it accept?
- How do you get the JSON Schema for a Pydantic model?
- What are the key differences between Pydantic v1 and v2 that affect FastAPI code?
- What is a discriminated union in Pydantic and when is it useful in FastAPI?
Validators
- How do you write a custom field validator in Pydantic v2?
- What are the `before`, `after`, `wrap` and `plain` modes for `@field_validator`?
- How do you validate multiple fields with a single `@field_validator`?
- What is `@model_validator` and when do you need it instead of `@field_validator`?
- When would you use `@model_validator(mode="before")` and what does it receive?
- How do you create a custom Pydantic type with its own validation logic?
- What does a `ValidationError` from Pydantic look like and how do you access its details?
- What is strict mode in Pydantic v2 and when would you enable it?
- How do you skip a validator when the field value is `None`?
- Must a Pydantic field validator return a value?
- What is `BeforeValidator` / `AfterValidator` in Pydantic v2 `Annotated` style?
- How do you validate that two related request models are consistent with each other in FastAPI?
Serialization
- How do you convert a Pydantic model to a Python dict?
- What does `model_dump_json()` do and when should you use it over `model_dump()`?
- How do you use aliases during serialisation (output) in Pydantic v2?
- How do you customise how a specific field is serialised with `@field_serializer`?
- What is `@model_serializer` and when would you use it?
- Why is `exclude_unset=True` important for PATCH endpoints?
- How do you configure Pydantic to encode custom types (like Decimal or UUID) to JSON?
- What is the exact serialisation flow when FastAPI returns a Pydantic model?
- How does Pydantic handle serialisation of nested models?
- How do you serialise a list of Pydantic models to JSON?
- How do you create a modified copy of a Pydantic model without mutating the original?
- How does Pydantic serialise Python Enum values?
- How do you customise the JSON Schema generated for a Pydantic model?
Settings Management
- What is `BaseSettings` and why use it for FastAPI configuration?
- How do you load configuration from a `.env` file with `BaseSettings`?
- How do you avoid re-reading environment variables on every request in FastAPI?
- Are `BaseSettings` environment variable names case-sensitive?
- How do you organise complex settings into nested groups with `BaseSettings`?
- How do you load secrets from files (e.g., Docker secrets) with `BaseSettings`?
- How do you override settings values in tests?
- Can you add validators to `BaseSettings` fields?
- What is the singleton pattern for settings in FastAPI and what is the risk of using a module-level instance?
- What Python types work well with `BaseSettings` for environment variables?
- How do you support different settings for development, staging and production?
- Is `BaseSettings` included in Pydantic itself and what do you need to install?
FastAPI Dependency Injection
Depends Basics
- What is `Depends()` in FastAPI and why is it useful?
- Can a dependency function accept its own parameters (path, query, headers)?
- Can a dependency depend on another dependency (sub-dependencies)?
- If two dependencies declare `Depends(get_db)`, how many times is `get_db` called?
- How do you create a class-based dependency in FastAPI?
- Can a callable object instance be used as a FastAPI dependency?
- What is the `Depends()` shorthand and when can you use it?
- How do you apply a dependency to a route without using its return value?
- How do you apply a dependency globally to every route in the app?
- What types can a dependency function return?
- What happens if a dependency raises an `HTTPException`?
- How do you override a dependency in tests?
Advanced Dependencies
- What is a yield dependency in FastAPI and what problem does it solve?
- How do you write an async yield dependency?
- What happens in a yield dependency if the handler raises an exception?
- What happens when multiple yield dependencies are active in the same request?
- Can a yield dependency's teardown access the response or run background tasks?
- When should you use middleware vs a dependency for cross-cutting concerns?
- How do you create a parameterised dependency (different instances with different config)?
- How do you turn an existing async context manager into a FastAPI dependency?
- Is dependency caching per-request or across requests?
- In what order do global dependencies, middleware, and router dependencies execute?
- How do FastAPI security utilities (`OAuth2PasswordBearer`, `HTTPBearer`) relate to `Depends()`?
- How do you access the raw `Request` object inside a FastAPI dependency?
Lifespan & App State
- What is the `lifespan` parameter in FastAPI and what does it replace?
- Why are `@app.on_event("startup")` decorators deprecated and what should you use instead?
- How do you share objects (DB pool, HTTP client) across all requests in FastAPI?
- Show the standard pattern for initialising an async SQLAlchemy engine in lifespan.
- How do you compose multiple startup/shutdown concerns without one giant lifespan function?
- How do you access `app.state` from inside a dependency or middleware?
- How do you test lifespan events in FastAPI?
- What happens if an exception is raised during startup in the `lifespan` function?
- Can `APIRouter` have its own lifespan?
- How do you run a background task continuously from application startup?
- What is `request.state` and how does it differ from `app.state`?
FastAPI Security & Auth
OAuth2
- What is `OAuth2PasswordBearer` in FastAPI and what does it do?
- How do you implement the `/token` endpoint for the OAuth2 password flow in FastAPI?
- How do you hash and verify passwords securely in FastAPI?
- Show the standard pattern for a `get_current_user` dependency in FastAPI.
- How do you implement OAuth2 scopes in FastAPI?
- How do you block inactive or disabled users from accessing protected routes?
- How would you implement refresh tokens in a FastAPI application?
- How do you implement logout / token revocation for JWT-based auth in FastAPI?
- Why does the OAuth2 `/token` endpoint accept form data instead of JSON?
- How do you implement cookie-based authentication in FastAPI?
- How would you add TOTP two-factor authentication to a FastAPI app?
JWT Tokens
- What is a JWT and what are its three parts?
- How do you encode and decode a JWT in a FastAPI app?
- How does JWT expiry work and how does FastAPI check it?
- What standard JWT claims should you include and what do they mean?
- What is the difference between HS256 and RS256 JWT signing and when do you use each?
- What is the JWT algorithm confusion attack and how does FastAPI prevent it?
- What is the JWT "none" algorithm attack?
- Where should JWTs be stored on the client side, and what are the security trade-offs?
- What is refresh token rotation and why is it more secure than long-lived access tokens?
- How do you decode a JWT payload without verifying the signature, and when is this safe?
- What are the practical size limits for JWT tokens and how do they affect HTTP?
API Keys
- How do you implement API key authentication via a header in FastAPI?
- How do you accept an API key as a query parameter in FastAPI?
- How do you use `APIKeyCookie` for session-based authentication?
- How do you support multiple authentication methods (header key or Bearer token) on the same endpoint?
- Why must FastAPI APIs run over HTTPS and how do you enforce it?
- What is CORS and how do you configure it in FastAPI?
- When is CSRF protection needed in a FastAPI application and how do you implement it?
- How do you implement rate limiting in FastAPI?
- How do you prevent API keys and tokens from appearing in FastAPI logs?
- What does `TrustedHostMiddleware` do in FastAPI?
- How does FastAPI/Pydantic help prevent SQL injection, and what should you still watch out for?
FastAPI Database Integration
SQLAlchemy (Sync)
- How do you set up SQLAlchemy with FastAPI for synchronous use?
- How do you define a SQLAlchemy ORM model and map it to a Pydantic response model?
- When should you call `db.commit()` and `db.rollback()` in a FastAPI route?
- What are the main SQLAlchemy query patterns used in FastAPI routes?
- How do you handle SQLAlchemy relationships in FastAPI responses?
- What is the N+1 query problem and how do you avoid it in FastAPI?
- What is the correct scope for a SQLAlchemy session in FastAPI?
- What is the recommended project structure for SQLAlchemy + FastAPI?
- How does SQLAlchemy's connection pool interact with a multi-worker FastAPI deployment?
- How do you create database tables from SQLAlchemy models in FastAPI?
- How do you implement soft deletes in a SQLAlchemy + FastAPI application?
Async Database
- Why use async database drivers with FastAPI instead of sync SQLAlchemy?
- How do you set up an async SQLAlchemy engine and session for FastAPI?
- How do you write the `get_async_db` dependency for async SQLAlchemy?
- What are the key async query patterns with SQLAlchemy async?
- How do you load SQLAlchemy relationships in async code?
- What async PostgreSQL drivers work with SQLAlchemy and FastAPI?
- How do you use SQLite with async FastAPI (e.g., for testing)?
- What is `async_scoped_session` and when would you use it?
- How do you run synchronous SQLAlchemy operations inside an async context?
- How does the async SQLAlchemy connection pool behave with multiple Uvicorn workers?
- How do you manage database transactions explicitly in async SQLAlchemy?
Alembic Migrations
- What is Alembic and why do you use it with FastAPI instead of `create_all`?
- How do you initialise Alembic in a FastAPI project?
- What changes do you make to `alembic/env.py` to support autogenerate?
- How do you auto-generate a migration script with Alembic?
- How do you apply and roll back Alembic migrations?
- How do you configure Alembic to run async migrations (asyncpg)?
- What is the best practice for running Alembic migrations in production?
- How do you write a data migration in Alembic (not just schema changes)?
- What is a merge migration in Alembic and when do you need one?
- What is the `alembic_version` table and what does it contain?
- What does `alembic stamp` do and when would you use it?
- How do you test Alembic migrations in a CI pipeline?
FastAPI Testing
TestClient
- What is `TestClient` in FastAPI and how do you use it?
- How do you ensure lifespan events (startup/shutdown) run in tests?
- How do you set up a pytest fixture for a FastAPI `TestClient`?
- How do you send a JSON body in a TestClient POST request?
- How do you send custom headers (e.g., Authorization) in TestClient?
- How do you test query parameters with TestClient?
- How do you send cookies and test cookie-based auth with TestClient?
- How do you test form data submission with TestClient?
- How do you test that FastAPI returns 422 for invalid input?
- What is `raise_server_exceptions` and when should you disable it?
- Does TestClient follow redirects by default and how do you control this?
- How do you replace a database dependency with an in-memory fake in tests?
Async Testing
- Why do you need special handling for async tests in FastAPI?
- How do you configure `pytest-anyio` for FastAPI async tests?
- How do you use `httpx.AsyncClient` to test a FastAPI app?
- How do you add auth headers to an `httpx.AsyncClient` for multiple test requests?
- How do you create an async database fixture for FastAPI integration tests?
- How do you test WebSocket endpoints in FastAPI?
- What is event loop scope in pytest-asyncio/anyio and why does it matter?
- Can FastAPI tests run on Trio instead of asyncio?
- How do you mock an async function dependency in a FastAPI test?
- How do you test that a BackgroundTask was scheduled and optionally verify it ran?
- How do you test the exact JSON shape of a FastAPI response (snapshot testing)?
Dependency Overrides
- What is `app.dependency_overrides` and how do you use it in tests?
- How do you ensure dependency overrides don't leak between tests?
- Does the override function need the same signature as the original dependency?
- How do you override `BaseSettings` in tests using dependency overrides?
- Show the standard pattern for replacing the DB session dependency in tests.
- How do you mock an external HTTP API call injected as a dependency?
- How do you override only part of a dependency chain (one level deep)?
- How do you override a class-based dependency in FastAPI tests?
- How do you apply a dependency override to only one test without affecting others?
- How do you verify that a dependency was called with specific arguments in a test?
- Can you use a yield function as a dependency override?
FastAPI Deployment & Middleware
Uvicorn & Gunicorn
- What is Uvicorn and why is it the recommended server for FastAPI?
- Why combine Gunicorn with Uvicorn workers and how do you configure it?
- How many workers should you run per server for a FastAPI app?
- What is the difference between concurrency and parallelism in the context of FastAPI?
- How do you enable hot reload in Uvicorn for development?
- What is the recommended Dockerfile structure for a FastAPI application?
- How do you add a health check endpoint in FastAPI for container orchestration?
- How does FastAPI/Uvicorn handle graceful shutdown?
- How do you pass environment variables to a FastAPI app running in Docker?
- How do you serve multiple FastAPI apps from a single Uvicorn process?
- How do you run Uvicorn with SSL/TLS in development?
Middleware
- What is middleware in FastAPI and how does it wrap requests?
- What order does middleware execute in FastAPI?
- How do you configure CORS middleware in FastAPI and what are the critical settings?
- How do you enable GZip compression for FastAPI responses?
- What does `TrustedHostMiddleware` do and why is it important?
- How do you redirect all HTTP traffic to HTTPS in FastAPI?
- What is `BaseHTTPMiddleware` and what is its performance trade-off?
- Can middleware catch exceptions raised by route handlers?
- How do you implement a request ID middleware for distributed tracing?
- How do you add server-side sessions to FastAPI?
- How do you implement rate limiting as middleware in FastAPI?
- Should authentication be done in middleware or as a dependency?
Background Tasks
- What are `BackgroundTasks` in FastAPI and how do you use them?
- Can background tasks in FastAPI be async functions?
- In what order do multiple `BackgroundTasks` run?
- What happens if a background task raises an exception in FastAPI?
- When should you use `BackgroundTasks` vs a proper task queue like Celery?
- How do you integrate Celery with a FastAPI application?
- What is ARQ and why might you prefer it over Celery for a FastAPI app?
- How do you use a database session inside a FastAPI background task?
- How do you run a periodic/scheduled task in FastAPI?
- How do you return a task ID and let clients poll for the result in FastAPI?
- What is a common memory leak pattern with FastAPI background tasks?
More ways to practice
The self-quiz is live. Get notified when mock interviews and new question packs drop.
or
Join our WhatsApp Channel