Async • Pydantic • Dependencies • Production • 2026

FastAPI Interview Questions

⚡ 20 questions 🧭 What each one tests, an answer frame, a spoken answer ⏱️ 24 min read

FastAPI interviews for Python backend roles check whether you understand what the framework does for you and what it does not: async on the event loop, Pydantic validation, dependency injection, and the plumbing around a real service. The questions below cover what comes up most, each with what the interviewer is testing, an answer frame and a short spoken answer.

Easy Fundamentals Practice Question

1. What is FastAPI, and where does its speed come from?

What the interviewer is really testing:
Whether you know what sits underneath rather than repeating the tagline.
Answer frame:

Stack: an ASGI framework built on Starlette for the web layer and Pydantic for data validation.

Speed: ASGI plus async handlers on an event loop, so one worker serves many concurrent I/O-bound requests; Pydantic's validation core is compiled.

Productivity: type hints drive validation, serialisation and the automatic OpenAPI docs.

Sample spoken answer:

"FastAPI is a thin layer over Starlette, which handles ASGI routing and middleware, and Pydantic, which validates and serialises data from Python type hints. It is fast in two senses: request handling is asynchronous, so a single process can juggle many waiting requests, and the same type hints that validate input also generate the OpenAPI docs, so you write less code. The heavy lifting in validation runs in compiled code."

Red flag to avoid:

Saying it is fast because it is written in C, or not knowing Starlette exists.

Medium Async Practice Question

2. When should an endpoint be async def, and what happens if you call a blocking library inside it?

What the interviewer is really testing:
The most common FastAPI production bug; interviewers ask it almost every time.
Answer frame:

async def: runs on the event loop; use it when everything you await is async, such as an async HTTP client or database driver.

Blocking inside async: a synchronous database call or time.sleep freezes the loop and stalls every other request.

Plain def: FastAPI runs it in a thread pool, so blocking libraries are safe there; or offload with run_in_threadpool.

Sample spoken answer:

"I use async def when the work inside is genuinely awaitable, like an async database driver or HTTP client. If I call a blocking library inside an async def, the whole event loop stops while it runs, so every other request in that worker waits. When I only have synchronous libraries I declare the endpoint with plain def, which FastAPI runs in a thread pool, or I push the blocking call into the thread pool explicitly."

Red flag to avoid:

Making everything async def 'because it is faster'.

Easy Validation Practice Question

3. How do Pydantic models handle request validation and response serialisation?

What the interviewer is really testing:
Basics of the data layer.
Answer frame:

Input: a model in the signature is parsed from the body, types coerced and constraints checked; failures return a 422 with field-level errors.

Output: response_model filters and serialises what goes out, so internal fields never leak.

Custom rules: field and model validators for cross-field checks.

Sample spoken answer:

"If a parameter is a Pydantic model, FastAPI reads the JSON body, validates every field against the types and constraints, and returns a 422 with a precise error list if anything is wrong, so my handler only ever sees valid data. On the way out, response_model decides which fields are serialised, which is how I keep password hashes and internal ids out of responses. For rules that span fields I add a model validator."

Red flag to avoid:

Returning the database model directly with no response schema.

Medium Dependencies Practice Question

4. What is dependency injection in FastAPI, and how do you use Depends?

What the interviewer is really testing:
The framework's central pattern; this reveals how you structure code.
Answer frame:

Mechanism: Depends(func) tells FastAPI to call func, resolving its own parameters the same way, and pass the result in.

Uses: current user, database session, settings, pagination parameters, permission checks.

Yield dependencies: code after yield runs at the end of the request for cleanup; dependencies are cached per request.

Sample spoken answer:

"Depends lets me declare that an endpoint needs something, like the current user or a database session, and FastAPI builds it by calling a function whose own parameters are resolved the same way, so dependencies can nest. With yield I get setup and teardown around the request, which is how I open and close a session. The result is cached within one request, so two parameters asking for the same dependency share it."

Red flag to avoid:

Using global objects and module-level state instead of dependencies.

Easy Fundamentals Practice Question

5. How does FastAPI decide whether a parameter is a path, query or body parameter?

What the interviewer is really testing:
Quick sanity check that you have read the docs.
Answer frame:

Path: the name appears in the route path.

Query: a simple type such as int or str not in the path.

Body: a Pydantic model; explicit Body, Query, Path, Header and Cookie override the defaults, usually via Annotated.

Sample spoken answer:

"If the parameter name is in the path template it is a path parameter. A simple type like an int or a string that is not in the path becomes a query parameter. A Pydantic model is read from the JSON body. When I need something else, for example a single value from the body or a header, I annotate it explicitly with Body, Header and so on."

Red flag to avoid:

Not knowing that a single simple-type parameter comes from the query string.

Medium Security Practice Question

6. How do you implement authentication with OAuth2 and JWT in FastAPI?

What the interviewer is really testing:
Whether you can wire the standard flow and know where the real security lives.
Answer frame:

Token endpoint: accept username and password with the OAuth2 password form, verify the hash, issue a signed JWT with an expiry.

Protect routes: an OAuth2PasswordBearer dependency reads the bearer header; a get_current_user dependency decodes and validates the token.

Care points: hash passwords properly, short-lived access tokens, refresh tokens or sessions, secrets from the environment.

Sample spoken answer:

"I expose a token endpoint that takes the OAuth2 password form, checks the password against a stored hash, and returns a signed JWT with an expiry. Protected routes depend on a get_current_user function that reads the bearer token through OAuth2PasswordBearer, verifies the signature and expiry, and loads the user, so a bad token never reaches the handler. The important parts are not framework specifics: a strong password hash, short token lifetimes, and the signing key kept out of the code."

Red flag to avoid:

Storing plain passwords, tokens that never expire, or the secret key in the repository.

Easy Documentation Practice Question

7. How are the automatic API docs generated, and how do you customise them?

What the interviewer is really testing:
Whether you use the docs as a product artefact, not just a demo.
Answer frame:

Source: the OpenAPI schema is generated from routes, type hints and Pydantic models; Swagger UI and ReDoc render it.

Customise: app title and version, tags per router, summaries and descriptions, example values, documented error responses.

Control: hide internal routes with include_in_schema=False, or disable the docs in production if required.

Sample spoken answer:

"FastAPI builds an OpenAPI document from the routes, the parameter types and the Pydantic models, and serves it with Swagger UI and ReDoc. I make it useful by tagging routers, writing summaries and descriptions on endpoints, adding example values to the models, and declaring the error responses each endpoint can return so clients see them. Internal endpoints get excluded from the schema."

Red flag to avoid:

Never having looked at the generated docs beyond the default page.

Medium Architecture Practice Question

8. How do you structure a large FastAPI project?

What the interviewer is really testing:
Whether you can keep a service maintainable past the tutorial stage.
Answer frame:

Routers: one APIRouter per domain with a prefix and tags, included in the app.

Layers: schemas for I/O, models for the database, services for business logic, repositories for queries; handlers stay thin.

Config and wiring: settings from the environment via a settings model, dependencies for sessions and clients, tests per layer.

Sample spoken answer:

"I split by domain, each with its own router, Pydantic schemas, database models and a service module that holds the logic. Handlers only parse input, call a service and shape the response. Settings come from the environment through a typed settings object, database sessions and external clients are provided through dependencies, and that layering means I can test the services without HTTP and the handlers with dependency overrides."

Red flag to avoid:

One main file with all routes and database calls inline.

Medium Async Practice Question

9. BackgroundTasks or a job queue: when is each the right choice?

What the interviewer is really testing:
Judgement about durability.
Answer frame:

BackgroundTasks: runs after the response in the same process; fine for quick, best-effort work like sending a notification.

Queue: a worker system such as Celery, RQ or ARQ when work must survive a restart, be retried, or take a long time.

Rule: if losing the task on a crash would matter, it needs a queue.

Sample spoken answer:

"BackgroundTasks is just a function that runs after the response is sent, inside the web process. It is right for small best-effort things like an audit log write or a notification. It is not durable: if the process restarts the task is gone, and long tasks tie up the worker. Anything that must happen, can fail and needs a retry, or takes minutes goes to a proper queue with workers."

Red flag to avoid:

Running payment or email retries in BackgroundTasks.

Hard Databases Practice Question

10. How do you manage database sessions with SQLAlchemy in FastAPI, including async?

What the interviewer is really testing:
Where most real-world FastAPI bugs live: leaked sessions, blocked loops, lost transactions.
Answer frame:

One session per request: a yield dependency opens a session, yields it, commits or rolls back, and closes it.

Async: the async engine with an async driver and AsyncSession; every query awaited; never a sync session inside async def.

Pooling: the engine is created once at startup; sessions are cheap, connections are pooled.

Sample spoken answer:

"I create the engine once at application startup and provide a session through a dependency that yields it, commits on success, rolls back on an exception and always closes. For async endpoints I use the async engine with an async driver and AsyncSession, and every query is awaited, because a synchronous session inside an async handler would block the loop. The unit of work is the request, so a handler never has to think about opening or closing anything."

Red flag to avoid:

A global session shared by all requests, or forgetting to close on exceptions.

Medium Lifecycle Practice Question

11. What is the lifespan handler, and what belongs in it?

What the interviewer is really testing:
Whether you know the current way to run startup and shutdown code.
Answer frame:

Mechanism: an async context manager passed as lifespan to the app; code before yield runs at startup, after it at shutdown.

Belongs: creating the database engine, HTTP client pools, caches, loading a model; closing them on shutdown.

Note: it replaces the older startup and shutdown event decorators.

Sample spoken answer:

"Lifespan is an async context manager that FastAPI enters when the app starts and exits when it stops. Before the yield I build long-lived resources, like the database engine, a shared HTTP client, or a loaded ML model, and store them on the app state; after the yield I close them cleanly. It replaced the separate startup and shutdown event hooks, and it is also what the test client runs when used as a context manager."

Red flag to avoid:

Creating a new database engine per request.

Easy Middleware Practice Question

12. How do middleware and CORS work in FastAPI?

What the interviewer is really testing:
Basic request pipeline knowledge.
Answer frame:

Middleware: wraps every request and response; used for logging, timing, request ids, auth headers.

CORS: add CORSMiddleware with explicit allowed origins, methods and headers; the browser enforces it, the server only declares it.

Caution: the simple HTTP middleware base class has overheads; pure ASGI middleware is better for hot paths.

Sample spoken answer:

"Middleware sits around the whole app: it sees each request before the router and each response on the way out, so it is where I put request ids, timing and structured logging. CORS is a middleware too; I list the exact origins allowed and the methods and headers, because a wildcard with credentials is not allowed by browsers anyway. For anything performance-sensitive I write pure ASGI middleware instead of the convenience base class."

Red flag to avoid:

Allowing all origins with credentials, or not knowing CORS is enforced by the browser.

Medium Errors Practice Question

13. How do you handle errors and return consistent error responses?

What the interviewer is really testing:
Whether your API is pleasant for clients to consume.
Answer frame:

HTTPException: for expected client errors with a status code and detail.

Custom handlers: exception_handler for domain exceptions, mapping them to a consistent JSON shape.

Validation errors: override the handler for request validation errors if the default 422 body does not fit; never leak stack traces.

Sample spoken answer:

"For normal client errors I raise HTTPException with the right status and a message. For domain errors, like an insufficient balance, I raise my own exception types from the service layer and register handlers that translate them into one consistent error JSON shape with a code and a message. I also register a handler for validation errors so the 422 body matches that shape, and unexpected exceptions become a generic 500 with the details only in the logs."

Red flag to avoid:

Catching all exceptions in every handler, or returning stack traces to clients.

Medium Testing Practice Question

14. How do you test a FastAPI application?

What the interviewer is really testing:
Whether you can test at the right level without a running server.
Answer frame:

TestClient: calls the app in-process with a familiar requests-style API; use it as a context manager so lifespan runs.

Async tests: an async HTTP client with the ASGI transport when tests themselves must be async.

Overrides: app.dependency_overrides swaps the database session, the current user or an external client for a test double.

Sample spoken answer:

"I use the test client, which calls the app directly without a network, and I open it as a context manager so startup code runs. For async test suites I use an async HTTP client pointed at the app through the ASGI transport. The key tool is dependency overrides: I replace the session dependency with one that uses a test database in a rolled-back transaction, and the current-user dependency with a fixed user, so tests are fast and isolated."

Red flag to avoid:

Tests that start a real server and hit production services.

Medium Validation Practice Question

15. Why should input and output schemas be separate models?

What the interviewer is really testing:
Schema design judgement.
Answer frame:

Different shapes: create needs a password, read never returns it; update makes fields optional; the id exists only on output.

Security: a shared model invites mass assignment and field leakage.

Pattern: a base model with shared fields, then Create, Update and Read models that extend it; from_attributes to read from ORM objects.

Sample spoken answer:

"The input and output of the same resource are genuinely different: a create request carries a password and no id, a response carries an id and never the password, and an update makes most fields optional. Using one model for all of them either leaks fields or lets clients set things they should not. I define a base with the shared fields and derive Create, Update and Read models from it, and the Read model is configured to load from ORM objects."

Red flag to avoid:

One model for the table, the request and the response.

Medium Deployment Practice Question

16. How do you run FastAPI in production?

What the interviewer is really testing:
Operational competence.
Answer frame:

Server: Uvicorn workers, either directly with multiple workers or managed by Gunicorn with the Uvicorn worker class.

Around it: a reverse proxy or load balancer terminating TLS, health check endpoints, graceful shutdown, structured logs.

Packaging: a container with a non-root user, settings from the environment, no reload mode.

Sample spoken answer:

"I run Uvicorn with several worker processes, sized to the CPU count, usually under Gunicorn as the process manager in a container. TLS and routing happen at a reverse proxy in front. The app exposes a health endpoint, handles shutdown signals so in-flight requests finish, and logs in a structured format. Configuration comes from environment variables, never from files in the image."

Red flag to avoid:

Running the development server with reload in production, or a single worker for a CPU-heavy service.

Hard Validation Practice Question

17. What changed between Pydantic v1 and v2 that a FastAPI developer must know?

What the interviewer is really testing:
Whether you maintain real code that survived the migration.
Answer frame:

Names: parse_obj became model_validate, dict became model_dump, validator became field_validator and model_validator.

Config: class Config became model_config = ConfigDict(...); orm_mode became from_attributes.

Behaviour: a compiled validation core, stricter defaults in some coercions, and settings moved to the separate pydantic-settings package.

Sample spoken answer:

"Version two renamed the core methods: model_validate and model_dump replace parse_obj and dict, and validators became field_validator and model_validator with slightly different signatures. Configuration moved to model_config with ConfigDict, and orm_mode is now from_attributes. Validation runs in a compiled core so it is much faster, a few coercions became stricter, and the settings class lives in the pydantic-settings package. FastAPI supports both, but mixing styles in one codebase is where migrations go wrong."

Red flag to avoid:

Not knowing the migration happened, or using deprecated names in new code.

Medium Async Practice Question

18. How do you stream a response, and how do WebSockets work in FastAPI?

What the interviewer is really testing:
Whether you can go beyond request-response.
Answer frame:

Streaming: return a StreamingResponse wrapping an async generator; useful for large files, server-sent events and token-by-token LLM output.

WebSockets: a websocket route accepts the connection, then loops on receive and send; handle WebSocketDisconnect.

Operations: streaming ties up a connection, so mind timeouts at the proxy and worker counts.

Sample spoken answer:

"For streaming I return a StreamingResponse built from an async generator, so chunks go out as they are produced, which is how I stream model output as server-sent events. For two-way traffic I declare a websocket route, accept the connection, and loop receiving and sending messages until the client disconnects, which raises a disconnect exception I catch to clean up. In both cases I check proxy timeouts, because long-lived connections are exactly what default proxy settings cut off."

Red flag to avoid:

Building the whole response in memory and calling it streaming.

Medium API Design Practice Question

19. How would you add rate limiting and pagination to a FastAPI service?

What the interviewer is really testing:
Practical API design beyond the framework.
Answer frame:

Rate limiting: not built in; a dependency or middleware with a shared store such as Redis, or at the gateway; return 429 with a retry hint.

Pagination: offset and limit for simple cases; cursor-based for large or changing lists; validate bounds with Query constraints.

Consistency: a shared pagination dependency and a common response envelope.

Sample spoken answer:

"FastAPI does not ship a rate limiter, so I either do it at the gateway or write a dependency that checks a counter in Redis per key and returns 429 with a retry-after header. For pagination I write one dependency that parses page and size with validated bounds, and for big or fast-changing lists I switch to cursor pagination so pages stay stable. Every list endpoint returns the same envelope with items and a next cursor."

Red flag to avoid:

An in-memory rate limiter in a multi-worker deployment.

Medium Architecture Practice Question

20. FastAPI, Django REST Framework or Flask: how do you choose?

What the interviewer is really testing:
Judgement, not loyalty.
Answer frame:

FastAPI: API-first services, async I/O, typed contracts and docs out of the box.

Django with DRF: when you want the batteries, ORM, admin, auth and a large team convention; async is partial.

Flask: small services and maximum freedom; you assemble everything yourself.

Sample spoken answer:

"If I am building an API-first service that talks to other services and does a lot of I/O, FastAPI is the default for me: typed contracts, async and docs for free. If the product needs an admin, a mature ORM, permissions and a big team that benefits from convention, Django REST Framework is hard to beat, even though async support is partial. Flask is for small things where I want to choose every piece myself."

Red flag to avoid:

Dismissing Django as old, or not knowing FastAPI has no ORM or admin of its own.

Undetectable AI for live interviews

Crack your FastAPI interview, no matter how tough

Backend interviews go from 'why is it fast' to 'what happens if you call a blocking library inside async def' to 'how do you test that dependency' without a pause. The follow-ups are the interview, and the frame has to be ready.

ClapAssist is your silent co-pilot. Runs natively on macOS and Windows, listens to the interviewer's exact question, and surfaces concise talking points right next to your camera eye-line. Excluded at the OS level from Zoom, Google Meet, and Teams screen sharing.

Download ClapAssist with 10 Free Minutes →
Mac & Windows · Completely undetectable to interviewers · No credit card required