FastAPI interview questions and answers, from Pydantic to async
FastAPI interview questions focus on three things: how type hints and Pydantic models turn into validation and OpenAPI docs, how the Depends system wires in database sessions and auth, and when a route should be async def or plain def. Experienced Python backend candidates also get blocking calls inside the event loop, lifespan setup, testing with dependency overrides and running the app behind an ASGI server. Answers that show you know what runs on the event loop and what runs in the thread pool stand out.
By Evin JohnPublished 9 min read
Where FastAPI comes up
FastAPI questions appear in Python backend interviews, in machine learning platform roles where models are served over HTTP, and in startups that picked it for typed APIs with generated docs. Interviewers rarely ask you to recite decorators. They hand you a half-built service and ask you to add an endpoint with validation, inject a session, protect a route, or find why latency spikes under load. For a framework comparison, expect at least one question on Flask and Django and why a team picked FastAPI.
- ScreenPython basics plus FastAPI concepts: parameter types, Pydantic models, status codes, what ASGI is.
- Build roundAdd CRUD endpoints to a small service with a database session dependency, input and output models and tests, live or as a take-home.
- Debugging or designDiagnose a slow endpoint (often a blocking call in async def), design auth, background work and deployment, or scale the service behind a load balancer.
Fundamentals: parameters, models and responses
| Question | What it tests | What a strong answer shows |
|---|---|---|
| How does FastAPI decide whether a parameter comes from the path, the query or the body? | Parameter sources | Names in the path template are path parameters. Simple typed parameters not in the path are query parameters. Parameters typed as a Pydantic model are read from the JSON body. Query, Path, Header, Cookie and Body make the source explicit and add constraints. |
| What happens when a request fails validation? | Error contract | FastAPI returns a 422 with a detail list naming each field, its location and the reason, before your function runs. |
| What is response_model for? | Output shaping | It validates and filters what you return, so a password hash on the ORM object does not leak, and it documents the response in OpenAPI. |
| Where do the /docs and /redoc pages come from? | OpenAPI | FastAPI builds an OpenAPI schema from routes, type hints and models, and serves Swagger UI and ReDoc from it. You can turn them off in production. |
| How do you set a status code like 201 or 204? | HTTP semantics | status_code in the decorator for the normal case, or return a Response directly. Raise HTTPException for errors. |
| What is the relationship between FastAPI and Starlette? | Architecture | FastAPI is built on Starlette for routing, requests, middleware and WebSockets, and on Pydantic for data. Anything Starlette offers is available underneath. |
| What is ASGI and how is it different from WSGI? | Server model | WSGI is synchronous, one request per call. ASGI is the async interface that supports concurrent requests on an event loop, WebSockets and long-lived connections. Flask is classic WSGI; FastAPI is ASGI. |
| How do you split a large app into modules? | Structure | APIRouter per area, included with a prefix, tags and shared dependencies, plus separate modules for schemas, models and services. |
Pydantic models and validation
Many FastAPI answers are really Pydantic answers. Interviewers check whether you keep separate input and output models, how you add custom validation, and whether you know the Pydantic 2 method names. Current FastAPI releases work with Pydantic 2, and older codebases may still use version 1 names such as .dict() and @validator, so it helps to mention both when you describe a migration.
from pydantic import BaseModel, Field, ValidationError, field_validator
class UserCreate(BaseModel):
email: str
password: str = Field(min_length=12)
display_name: str | None = None
@field_validator("email")
@classmethod
def normalize_email(cls, value: str) -> str:
value = value.strip().lower()
if "@" not in value:
raise ValueError("not an email address")
return value
class UserPublic(BaseModel):
id: int
email: str
display_name: str | None = None
try:
UserCreate(email="Ana@Example.com", password="short")
except ValidationError as err:
print(err.errors()[0]["loc"], err.errors()[0]["type"])
# ('password',) string_too_short
ok = UserCreate(email=" Ana@Example.com ", password="a-long-passphrase")
print(ok.email) # ana@example.com
row = {"id": 7, "email": ok.email, "password_hash": "x", "display_name": None}
print(UserPublic.model_validate(row).model_dump())
# {'id': 7, 'email': 'ana@example.com', 'display_name': None}- Why use separate models for input and output? Clients should not send an id or read a password hash. A create model, an update model with optional fields, and a public model keep each contract honest.
- How do you make a partial update? An update model with every field optional, then model_dump(exclude_unset=True), so fields the client did not send are not overwritten with None.
- How do you return ORM objects? Set from_attributes in the model config (orm_mode in Pydantic 1) so the response model reads attributes instead of dict keys.
- How do you validate a rule that spans fields, such as start before end? A model validator that runs after field validation and raises ValueError with a clear message.
- What does Annotated add? It attaches metadata such as Query(max_length=50) or Depends(get_db) to a type, so the same annotated type can be reused across routes and the plain type hint stays correct.
Dependency injection with Depends
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
# Session, SessionLocal, User, OrderPublic, users and orders come from the app's own modules.
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
Db = Annotated[Session, Depends(get_db)]
def get_current_user(db: Db, token: Annotated[str, Depends(oauth2_scheme)]):
user = users.from_token(db, token)
if user is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid token")
return user
CurrentUser = Annotated[User, Depends(get_current_user)]
@app.get("/orders/{order_id}", response_model=OrderPublic)
def read_order(order_id: int, db: Db, user: CurrentUser):
order = orders.get(db, order_id)
if order is None or order.owner_id != user.id:
raise HTTPException(status_code=404, detail="order not found")
return order| Question | What it tests | What a strong answer shows |
|---|---|---|
| What does a dependency with yield do? | Resource lifetime | Code before yield runs before the route, the yielded value is injected, and code after it runs once the response is handled, even when the route raised. It is the standard way to open and close a session. |
| If two dependencies both need get_db, is it called twice? | Caching | No. Within one request FastAPI caches a dependency's result and reuses it, unless you pass use_cache=False. |
| How do you apply auth to a whole group of routes? | Router dependencies | Add the dependency to the APIRouter or include_router dependencies list, so every route in it runs the check. |
| How do you replace a dependency in tests? | Testability | Set app.dependency_overrides[get_db] to a function that yields a test session, and clear it after the test. |
| Why is dependency injection better here than a global session? | Design | Each request gets its own session and cleanup, tests can swap it, and the route signature shows what it needs. |
| Can classes be dependencies? | Callables | Yes. Anything callable works, so a class with __init__ parameters becomes a dependency that collects shared query parameters such as paging. |
Async, concurrency and performance
This is where FastAPI interviews separate people who used the framework from people who ran it in production. A route declared with async def runs directly on the event loop. If it calls a blocking library, such as a synchronous database driver, requests or time.sleep, the whole worker stops serving other requests until the call returns. A route declared with plain def is run in a thread pool, so blocking calls there are acceptable, within the pool's size.
- Should every route be async def? Only when everything it awaits is async: an async driver, httpx's async client, asyncio.sleep. If the code is blocking, plain def is the safer choice.
- Latency jumps for all endpoints when one slow endpoint gets traffic. What is your first guess? A blocking call inside async def. Confirm with a profiler or by timing the event loop, then switch the driver to async, move the call to a thread with run_in_threadpool, or make the route a plain def.
- When do you use BackgroundTasks and when a real queue? BackgroundTasks run in the same process after the response, fine for a quick email or log write. Anything long, retried or important goes to a queue such as Celery, RQ or a cloud queue, because a restart loses in-process tasks.
- How do you run CPU-heavy work, such as model inference? Not on the event loop. Use a process pool, a separate worker service, or a model server, and keep the API thin.
- How many workers should you run? Usually several processes per container or one process per container with horizontal scaling, depending on the platform. Each process has its own event loop; the GIL limits CPU work within one process.
- How do you stream a large response? StreamingResponse with a generator, so the file or query result is not held in memory at once.
App lifecycle, middleware, errors and security
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Where do you create a connection pool or load a model at startup? | Lifespan | In a lifespan async context manager passed to FastAPI: set up before yield, tear down after. It replaced the older startup and shutdown event handlers. |
| How do you return the same error shape everywhere? | Error handling | Custom exception classes plus app.exception_handler for each, and an override of the validation error handler if the client needs a different format than the default 422 body. |
| What would you put in middleware? | Cross-cutting concerns | Request ids, timing, CORS, compression, security headers. Not business rules; those belong in dependencies, which can see route parameters. |
| How do you configure CORS? | Browsers | CORSMiddleware with an explicit list of origins, methods and headers. A wildcard origin with credentials is not allowed by browsers and is a red flag in review. |
| How would you implement JWT auth? | Security | OAuth2PasswordBearer to read the bearer token, a dependency that verifies signature, expiry and audience, and short-lived access tokens with refresh handled separately. Hash passwords with a slow algorithm such as bcrypt or argon2. |
| How do you handle settings and secrets? | Configuration | A settings class from pydantic-settings that reads environment variables, cached with lru_cache and injected as a dependency, so tests can override it. |
| How do you add WebSockets? | Real time | A websocket route that accepts, loops on receive and send, and handles WebSocketDisconnect. Across several workers, broadcast through a shared broker such as Redis. |
Testing, deployment and comparisons
- How do you test endpoints? TestClient, built on httpx, calls the app in process. For async tests against async dependencies, use httpx's AsyncClient with an ASGI transport and an async test runner.
- How do you test with a real database without touching production data? A test database, a dependency override that yields a session inside a transaction, and a rollback after each test.
- How do you deploy a FastAPI app? A container running an ASGI server such as Uvicorn, often with several workers or under a process manager, behind a reverse proxy or load balancer that terminates TLS. Health check route, structured logs, and graceful shutdown on SIGTERM.
- How do you version an API in FastAPI? Routers mounted under /v1 and /v2 with separate schemas, and deprecation flags on old routes so the docs show it.
- FastAPI or Flask for a new service? FastAPI gives validation, docs and async support out of the box. Flask is smaller and mature with a large extension ecosystem, and fits sync apps well. Name the trade-off rather than declaring a winner.
- FastAPI or Django? Django brings an ORM, admin, auth and migrations as one package, ideal for content-heavy apps. FastAPI is a lean API layer where you choose the ORM, often SQLAlchemy or SQLModel.
Fictional example
- Interviewer
- Here is the new route. It is async def and calls requests.get on the pricing service. CPU is low. What happened?
- Candidate
- requests is blocking, and the route is async def, so the event loop waits on each pricing call and no other request on that worker moves. CPU stays low because the process is just waiting. The quickest fix is to make the route a plain def, which runs it in the thread pool. The better fix is httpx.AsyncClient created once in the lifespan, awaited in the route, with a timeout of a few hundred milliseconds and a fallback if pricing is slow. I would also check the database driver, because the same bug hides there. Then I would add a load test that hits this route alongside a cheap health route and alert on event loop lag, so the next blocking call shows up before users notice.
One-week FastAPI practice plan
- Day 1: build a CRUD service with create, update and public models, and read the generated docs to check every contract.
- Day 2: add a session dependency with yield, a current-user dependency, and a router-level auth dependency.
- Day 3: write tests with TestClient and dependency overrides, including a 422 case and a 404 case.
- Day 4: put a blocking sleep in an async route, load it with a simple tool, and watch every route slow down. Fix it two ways.
- Day 5: add lifespan setup, custom exception handlers, CORS and settings from the environment.
- Days 6 and 7: containerize it, run several workers, and practice the trade-off questions out loud.
If the role also lists another Python framework, compare with Flask interview questions and Django interview questions. For API design questions that do not depend on a framework (methods, status codes, pagination, idempotency) see REST API interview questions. Teams running a Node back end instead will ask what is on the Express.js interview questions page, and a Vue front end calling your API is covered in Vue.js interview questions.
When you rehearse, Natively, an AI interview assistant for Mac and Windows, can transcribe the mock round on your computer so you can review whether you explained the event loop or just said "use async". In practice sessions it can read a task or a traceback from a screenshot and suggest code, and with Pro or the free trial it draws on the résumé and job description you add. The transcript and notes are saved for review afterwards.
Questions people ask
What FastAPI questions are asked in interviews?
Expect parameter sources and validation, Pydantic input and output models, dependency injection with Depends and yield, async def versus def, lifespan setup, middleware and error handlers, JWT auth, testing with dependency overrides and deployment on an ASGI server.
When should a FastAPI route be async def instead of def?
Use async def only when the route awaits non-blocking libraries such as an async database driver or httpx's async client. If it calls blocking code, plain def is safer, because FastAPI runs it in a thread pool instead of stalling the event loop.
What is a dependency with yield in FastAPI?
A dependency that sets something up, yields it to the route and runs cleanup after the response is handled. It is the usual way to open and close a database session per request.
How is FastAPI different from Flask?
FastAPI is an ASGI framework that uses type hints for validation and generates OpenAPI docs automatically, with native async support. Flask is a WSGI microframework that leaves validation and docs to extensions.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
