FastAPI Interview Questions and Answers
Last updated 2026-11-19
FastAPI interviews check that you understand what the framework does for you from type hints: request parsing, validation, serialisation and OpenAPI docs. They also probe the places where it is easy to go wrong, such as blocking calls inside async routes, dependency scoping and handling database sessions.
This page uses Pydantic v2 and the current lifespan-based startup, plus the Annotated style for dependencies. If you are comparing with other Python frameworks, see the Flask and Django pages, and the backend developer questions for general API topics.
| Version covered | FastAPI 0.11x on Pydantic v2 and Python 3.10 and later |
|---|---|
| Core topics | Typing, validation, dependencies, async, security, testing |
| Questions here | 17 |
The async question you should expect
A route declared with async def runs on the event loop, so any blocking call inside it, such as a synchronous database driver, requests.get or time.sleep, stalls every other request. A route declared with plain def is run in a thread pool by FastAPI, so blocking code there is fine. Interviewers love this because the wrong choice makes a service slower than a synchronous one.
Pydantic v2 vocabulary
- model_validate and model_dump replace the older parse_obj and dict methods.
- ConfigDict(from_attributes=True) replaces orm_mode for reading from ORM objects.
- field_validator and model_validator replace validator and root_validator.
- Validation is implemented in Rust, which makes it much faster than v1.
FastAPI Interview Questions and Answers: questions with worked answers
1 What makes FastAPI different from Flask?
easyFastAPI is an ASGI framework built on Starlette and Pydantic. Type hints on path, query and body parameters drive validation, conversion and an automatic OpenAPI schema with interactive docs at /docs. It supports async natively, and invalid input returns a structured 422 response without extra code. Flask is WSGI, synchronous by default, and leaves validation to you.
pythonfrom fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int, q: str | None = None): return {"item_id": item_id, "q": q}2 How do you declare request bodies and responses with Pydantic?
easyDefine a BaseModel for the body and use it as a parameter type. FastAPI parses the JSON and validates it. Set response_model or a return type annotation to filter the output, which is how you avoid leaking fields such as password hashes. Set status_code on the decorator. Use separate input and output models.
pythonfrom pydantic import BaseModel, EmailStr, Field class UserIn(BaseModel): email: EmailStr password: str = Field(min_length=10) class UserOut(BaseModel): id: int email: EmailStr @app.post("/users", response_model=UserOut, status_code=201) async def create_user(user: UserIn): return await save(user)3 When do you use async def and when plain def?
mediumUse async def when the route awaits non-blocking I/O such as an async database driver or httpx.AsyncClient. Use def when you call blocking libraries, because FastAPI runs the function in a thread pool and the event loop stays free. Never call blocking code from async def. For CPU-heavy work use a process pool or a task queue, since neither option helps there.
4 How does dependency injection work with Depends?
mediumA dependency is a callable that FastAPI calls for you and whose result is passed to the route. Dependencies can have their own dependencies, are cached per request by default, and may use yield to run cleanup after the response, which is the pattern for database sessions. They are also the place for authentication, pagination parameters and permission checks. Dependencies can be overridden in tests.
pythonfrom typing import Annotated from fastapi import Depends async def get_db(): async with SessionLocal() as session: yield session DbDep = Annotated[AsyncSession, Depends(get_db)] @app.get("/users/{uid}") async def get_user(uid: int, db: DbDep): return await db.get(User, uid)5 How do you handle startup and shutdown?
mediumUse a lifespan async context manager passed to FastAPI. Code before yield runs at startup, such as creating a connection pool, and code after runs at shutdown. The older on_event decorators are deprecated. Store shared resources on app.state and read them in dependencies.
pythonfrom contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app: FastAPI): app.state.pool = await create_pool(DSN) yield await app.state.pool.close() app = FastAPI(lifespan=lifespan)6 How do you implement JWT authentication?
mediumUse OAuth2PasswordBearer to read the bearer token, a login route that checks a password hash and issues a signed token with an expiry, and a dependency that decodes it and loads the user. Use PyJWT or authlib, hash passwords with Argon2 or bcrypt, keep the secret in an environment variable, and return 401 with a WWW-Authenticate header on failure.
pythonoauth2 = OAuth2PasswordBearer(tokenUrl="token") async def current_user(token: Annotated[str, Depends(oauth2)]): try: payload = jwt.decode(token, SECRET, algorithms=["HS256"]) except jwt.PyJWTError: raise HTTPException(401, "invalid token", headers={"WWW-Authenticate": "Bearer"}) return await users.get(payload["sub"])7 What are path, query and body parameters, and how are they told apart?
mediumA name that appears in the path template is a path parameter. A parameter of a scalar type that is not in the path is a query parameter, and giving it a default makes it optional. A parameter typed as a Pydantic model is read from the JSON body. Use Query, Path, Body and Header helpers for constraints such as ge, max_length and aliases. Several body models are embedded under their parameter names.
8 How do you validate with Pydantic v2 validators?
mediumUse Field constraints for simple rules and field_validator or model_validator for custom logic. A field validator is a classmethod that returns the cleaned value or raises ValueError. model_validator with mode after checks relationships between fields. Validation errors become a 422 response listing the location and message for each failure.
pythonfrom pydantic import BaseModel, field_validator, model_validator class Booking(BaseModel): start: int end: int @model_validator(mode="after") def check_range(self): if self.end <= self.start: raise ValueError("end must be after start") return self9 How do you handle errors and customise error responses?
mediumRaise HTTPException with a status code and detail for expected failures. Register exception handlers with app.exception_handler for custom exception classes or to reshape validation errors from RequestValidationError. Return a consistent error format. Unexpected exceptions result in a 500, so add logging middleware or a handler that logs the traceback without leaking it.
10 What are BackgroundTasks and when are they not enough?
mediumBackgroundTasks run a function after the response is sent, in the same process, suited to small jobs like writing an audit log or sending a notification. They do not survive a crash or restart, have no retry or scheduling, and compete with request handling for resources. For reliable or heavy jobs use a queue and workers such as Celery, ARQ or a cloud queue.
11 How do you test FastAPI apps?
mediumUse TestClient from FastAPI, which wraps httpx, for synchronous tests, or httpx.AsyncClient with ASGITransport for async ones. Override dependencies through app.dependency_overrides to inject a test database or fake user. Run with pytest, and use a transaction rollback per test to keep the database clean.
pythonfrom fastapi.testclient import TestClient app.dependency_overrides[get_db] = lambda: fake_db client = TestClient(app) def test_read_item(): r = client.get("/items/3?q=x") assert r.status_code == 200 assert r.json() == {"item_id": 3, "q": "x"}12 How do you run FastAPI in production?
hardRun Uvicorn, or Gunicorn with Uvicorn workers, behind a reverse proxy or load balancer, with several worker processes sized to CPU cores, since each process runs one event loop. FastAPI also provides a fastapi run command. Set timeouts, configure structured logging and health checks, and containerise. Do not use the reload flag or the docs endpoints unprotected if the API is private.
13 How do you stream responses and use WebSockets?
hardReturn StreamingResponse with an async generator for large or incremental output such as server-sent events or file downloads. For two-way messaging declare a websocket route, accept the connection and loop receiving and sending messages, handling WebSocketDisconnect. With several workers you need a shared pub/sub such as Redis to broadcast to connections held by other processes.
pythonfrom fastapi import WebSocket, WebSocketDisconnect @app.websocket("/ws") async def ws(socket: WebSocket): await socket.accept() try: while True: msg = await socket.receive_text() await socket.send_text("echo: " + msg) except WebSocketDisconnect: pass14 How do you use SQLAlchemy 2 asynchronously with FastAPI?
hardCreate an async engine with a driver such as asyncpg, an async_sessionmaker with expire_on_commit=False, and provide a session through a yield dependency. Use await session.execute(select(...)) and eager-load relationships with selectinload, because lazy loading triggers implicit I/O that fails in async code. Run migrations with Alembic.
15 How do you version and organise a larger API?
hardSplit features into APIRouter modules with prefixes and tags and include them in the app. Version through a path prefix such as /v1, mounting sub-applications or routers per version, and keep response models stable within a version. Share dependencies for auth at router level with the dependencies argument. Document with OpenAPI summaries and examples.
16 What is the difference between a Pydantic model and a database model?
hardA Pydantic model validates and serialises data crossing the API boundary. An ORM model such as a SQLAlchemy class maps to a table and carries persistence behaviour. Keeping them separate lets the API shape evolve independently from the schema, and avoids exposing columns accidentally. Use model_config from_attributes=True to build the Pydantic output from an ORM object.
Frequently asked questions
Is FastAPI better than Flask or Django?
It depends. FastAPI suits typed JSON APIs with async I/O, Django suits full web apps with an admin and ORM, and Flask suits small flexible services.
Do I need to know async Python for FastAPI interviews?
Yes. Explain async versus sync routes, what blocks the event loop and how to use async clients and drivers.
What changed with Pydantic v2?
Faster Rust-based validation, renamed methods such as model_validate and model_dump, from_attributes instead of orm_mode, and new validator decorators.
Where does FastAPI get its docs from?
It generates an OpenAPI schema from route signatures and models, and serves Swagger UI at /docs and ReDoc at /redoc by default.
Related guides
More in Role-wise Interview Questions by Job and Tech Stack
- Flask Interview Questions and Answers
- Flutter Interview Questions and Answers (Flutter 3, Dart 3)
- Frontend Developer Interview Questions and Answers
- Full Stack Developer Interview Questions and Answers
- Generative AI and LLM Interview Questions and Answers
- Google Cloud (GCP) Interview Questions and Answers
- GraphQL Interview Questions and Answers
- Hibernate and JPA Interview Questions and Answers
- HTML and CSS Interview Questions and Answers
- iOS and Swift Interview Questions and Answers
- Jenkins and CI/CD Interview Questions and Answers
- Kubernetes Interview Questions and Answers