FastAPI interview questions test async Python and typed APIs: how FastAPI builds on Starlette (ASGI) and Pydantic, when to write async def or def, how dependency injection works, and how you validate, secure, test and deploy an API. FastAPI moves fast, so date your facts: on November 17, 2026 PyPI listed FastAPI 0.163.2, released that day. Its release notes show Pydantic v1 support dropped in 0.126.0 (December 20, 2025), and Python 3.10 support dropped in 0.162.6 (November 13, 2026), so current releases need Python 3.11 or later.
Below are 30 questions by level, five scenarios and how interviews test this. Language ground is in Python interview questions; the WSGI comparison is in Flask interview questions.
FastAPI interview questions: fundamentals (1–10)
- What is FastAPI? A Python framework for building APIs on Starlette (the ASGI toolkit) and Pydantic (validation). Type hints drive request validation, response serialization and the generated OpenAPI schema.
- ASGI versus WSGI? WSGI is synchronous, one request per worker thread. ASGI is its async successor and supports concurrent requests on an event loop, WebSockets and long-lived connections. FastAPI runs on ASGI servers such as Uvicorn.
- Path, query and body parameters? In
@app.get("/items/{item_id}")withdef read(item_id: int, q: str | None = None),item_idcomes from the path andqfrom the query string; a parameter typed as a Pydantic model is read from the JSON body. - How do Pydantic models validate input?
class Item(BaseModel): name: str; price: float = Field(gt=0). Invalid input never reaches your code; FastAPI returns 422 with a list of errors naming each field. - Where are the automatic docs? Swagger UI at
/docs, ReDoc at/redoc, and the schema at/openapi.json, all generated from your routes and models. - What does response_model do? It validates and filters the output, for example dropping a password field. Since 0.130.0, when a return type or response model is declared, FastAPI serializes the JSON with Pydantic's Rust core.
- How do you set status codes and errors?
@app.post("/items", status_code=201)for success, andraise HTTPException(status_code=404, detail="Item not found")for errors. - Why the Annotated style?
q: Annotated[str | None, Query(max_length=50)] = Nonekeeps metadata separate from the default value; FastAPI's docs use it throughout. - async def or def?
async defendpoints run on the event loop, so they must only await non-blocking calls. Plaindefendpoints run in a threadpool, so blocking libraries are safe there. A blocking call insideasync defstalls every request on that worker. - How do you run the app?
fastapi dev main.pyfor development with auto-reload, andfastapi run main.pyfor production, or Uvicorn directly withuvicorn main:app.
Intermediate FastAPI questions (11–20)
- How does Depends work? A dependency is a function or class whose parameters FastAPI resolves per request, including sub-dependencies. A dependency used several times in one request is cached by default. In tests, replace it with
app.dependency_overrides[get_db] = fake_db. - When does cleanup in a yield dependency run? Code after
yieldruns after the response is sent (the default"request"scope, restored in 0.118.0).Depends(get_db, scope="function"), added in 0.121.0, closes it right after the endpoint returns, before the response is sent. - How do you handle startup and shutdown? A lifespan context manager:
@asynccontextmanager async def lifespan(app): ...; yield; ...passed asFastAPI(lifespan=lifespan). Create clients and pools beforeyieldand close them after. - What are BackgroundTasks?
background_tasks.add_task(send_email, to)runs after the response, in the same process. Fine for small jobs; durable or heavy work belongs in a task queue. - How do you add middleware and CORS?
app.add_middleware(CORSMiddleware, allow_origins=["https://app.example.com"]), and@app.middleware("http")for custom logic such as timing headers or request IDs. - How do routers work?
APIRouter(prefix="/users", tags=["users"])per domain, included withapp.include_router(router). Since 0.137.0, included routers are kept rather than copied, so routes added after inclusion are still registered. - How do you secure endpoints? Security dependencies:
OAuth2PasswordBearer(tokenUrl="token")extracts a bearer token, and your dependency verifies it (for example as a JWT) and returns the user. Scopes, HTTP Basic and API keys follow the same pattern. - Which Pydantic version does FastAPI use? Pydantic v2. FastAPI dropped Pydantic v1 in 0.126.0 and the temporary
pydantic.v1compatibility in 0.128.0 (December 27, 2025). Use@field_validatorandmodel_config, the v2 APIs. - How do you customize error responses?
@app.exception_handler(MyError)returning aJSONResponse, and override theRequestValidationErrorhandler to change the 422 format. - How do you test a FastAPI app?
TestClient(app)for synchronous tests, or httpx'sAsyncClientwithASGITransportfor async tests, plusdependency_overridesfor the database and auth.
Experienced and senior FastAPI questions (21–30)
- How do you scale a FastAPI service? One event loop per worker process: run several workers (
fastapi run --workers 4) and several containers. Offload CPU-bound work to a process pool or a task queue, because it blocks the loop. - How do you use a database correctly? Async drivers (SQLAlchemy 2.0's asyncio support, asyncpg) inside
async def, or synchronous SQLAlchemy insidedefendpoints. Open one session per request through a yield dependency, and size connection pools per worker. - How do you stream responses?
StreamingResponseover a generator. Release notes show 0.134.0 added streaming JSON Lines and binary data withyield, and 0.135.0 added Server-Sent Events support. - How do WebSockets work?
@app.websocket("/ws")withawait websocket.accept(), then receive and send in a loop. Across several workers you need a broker such as Redis pub/sub. Since 0.144.0, security dependencies also work with WebSockets. - What are common performance mistakes? Blocking calls inside
async def, a new HTTP client per request instead of one created in the lifespan, no connection pooling, too few workers, and heavy validation of large responses that should be streamed. - How do you structure a large app? Routers per domain, shared dependencies in one module, settings from environment variables through
pydantic-settings, a service layer kept separate from route functions, and versioned prefixes such as/v1. - How do you limit concurrency for a fragile dependency? Recent FastAPI added this directly: 0.163.0 (November 14, 2026) introduced
Depends(..., max_concurrency=...). In older versions, guard the call with anasyncio.Semaphore. - How do you add observability? Structured logging with a request-ID middleware, metrics and tracing. FastAPI added native OpenTelemetry support in 0.142.0, and since 0.143.0 automatic exporter setup is opt-in.
- What changed for apps behind a path prefix? 0.146.0 (October 18, 2026) deprecated the
root_pathparameter ofFastAPI(); configure it on the server instead, for examplefastapi run --root-path /api/v1. - FastAPI, Flask or Django? FastAPI for typed, async APIs with automatic docs; Flask for minimal WSGI apps you assemble yourself; Django for full applications with ORM, admin and auth built in.
FastAPI scenario and troubleshooting questions
One slow endpoint makes the whole API slow. It probably calls a blocking library (such as requests or a sync database driver) inside async def, freezing the event loop. Switch to an async client such as httpx's AsyncClient, or make the endpoint a plain def.
A streaming endpoint fails because the database session is closed. The session dependency was declared with scope="function", which closes before the response streams. Use the default request scope, or open the session inside the generator.
The frontend gets 422 errors. Read the detail list: usually JSON versus form data (Form() is needed for forms), a field name mismatch, or a type error. Log the validation errors in a custom handler.
A routine dependency upgrade breaks the app. Check the release notes: pydantic.v1 imports were dropped in 0.128.0, Python 3.10 in 0.162.6, and ORJSONResponse was deprecated in 0.131.0. Pin versions and upgrade deliberately.
Open connections grow until the service crashes. An HTTP client or database engine is created per request and never closed. Create it once in the lifespan, share it through a dependency, and close it on shutdown.
How FastAPI interviews test this
| Format | What it usually looks like | How to prepare |
|---|---|---|
| Concept Q&A | async versus def, Depends, Pydantic validation, response_model, lifespan | Explain the event loop rule with one example |
| Live build | A CRUD API with validation, auth and tests, sometimes as a take-home | Build one end to end; see REST API interview questions |
| Code review | Spot a blocking call in async def, a client per request or a leaky dependency | Read the scenarios above as review prompts |
| System design | Serving an ML model or a high-traffic API with FastAPI | Talk workers, pools, timeouts and background queues |
If the role is Django-heavy, see Django interview questions.
Where CoPilot Interview fits
CoPilot Interview is an AI interview assistant. Its free AI mock interview builds FastAPI and Python backend questions from your résumé and the job description, reads them aloud and scores each spoken answer out of 10, which is a fast way to find the answers above that you know but cannot yet explain cleanly under pressure. The browser demo has 145 practice questions in 10 tracks, scores typed answers out of 10 and needs no signup. The free plan gives 15 minutes a day of live help in sessions of up to 15 minutes, with AI mock interviews included. Paid plans are Standard at $24.99 a month and Pro at $39.99 a month, in the desktop app for Windows 10/11 and macOS 12 or later.
Use it to practice. Online assessments, proctored tests, take-home tasks with rules and AI-led rounds forbid outside help, so prepare for those instead of bringing a tool. For any live interview, follow your employer's rules.
Disclosure: CoPilot Interview is our product, so weigh what we say about it accordingly.
Frequently asked questions
What are the most common FastAPI interview questions?
async def versus def, path, query and body parameters, Pydantic models and 422 errors, Depends and yield dependencies, response_model, lifespan events, background tasks, security dependencies and testing with TestClient.
Is FastAPI faster than Flask?
For I/O-bound APIs with many concurrent requests, an async ASGI app usually handles more concurrency per worker. Raw speed depends on your code, the server and the database far more than the framework.
Does FastAPI still support Pydantic v1?
No. Release notes show Pydantic v1 support dropped in 0.126.0 (December 2025) and the pydantic.v1 compatibility layer in 0.128.0.
What Python version does FastAPI need?
Python 3.11 or later for current releases; 0.162.6 (November 13, 2026) dropped Python 3.10, per FastAPI's release notes.
How do I prepare for a FastAPI interview?
Build an API with routers, a yield database dependency, JWT auth and async tests, then deliberately add a blocking call to an async endpoint and explain what happens under load.
Practice this interview before the real one
The AI mock interview builds questions from your resume and the job description, reads them aloud and scores each spoken answer out of 10. Included on the free plan.
Start a mock interview