Home › Blog › FastAPI Interview Questions (2026): 30 Questions on Async, Dependencies and Pydantic

FastAPI Interview Questions (2026): 30 Questions on Async, Dependencies and Pydantic

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.

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)

  1. 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.
  2. 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.
  3. Path, query and body parameters? In @app.get("/items/{item_id}") with def read(item_id: int, q: str | None = None), item_id comes from the path and q from the query string; a parameter typed as a Pydantic model is read from the JSON body.
  4. 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.
  5. 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.
  6. 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.
  7. How do you set status codes and errors? @app.post("/items", status_code=201) for success, and raise HTTPException(status_code=404, detail="Item not found") for errors.
  8. Why the Annotated style? q: Annotated[str | None, Query(max_length=50)] = None keeps metadata separate from the default value; FastAPI's docs use it throughout.
  9. async def or def? async def endpoints run on the event loop, so they must only await non-blocking calls. Plain def endpoints run in a threadpool, so blocking libraries are safe there. A blocking call inside async def stalls every request on that worker.
  10. How do you run the app? fastapi dev main.py for development with auto-reload, and fastapi run main.py for production, or Uvicorn directly with uvicorn main:app.

Intermediate FastAPI questions (11–20)

  1. 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.
  2. When does cleanup in a yield dependency run? Code after yield runs 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.
  3. How do you handle startup and shutdown? A lifespan context manager: @asynccontextmanager async def lifespan(app): ...; yield; ... passed as FastAPI(lifespan=lifespan). Create clients and pools before yield and close them after.
  4. 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.
  5. 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.
  6. How do routers work? APIRouter(prefix="/users", tags=["users"]) per domain, included with app.include_router(router). Since 0.137.0, included routers are kept rather than copied, so routes added after inclusion are still registered.
  7. 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.
  8. Which Pydantic version does FastAPI use? Pydantic v2. FastAPI dropped Pydantic v1 in 0.126.0 and the temporary pydantic.v1 compatibility in 0.128.0 (December 27, 2025). Use @field_validator and model_config, the v2 APIs.
  9. How do you customize error responses? @app.exception_handler(MyError) returning a JSONResponse, and override the RequestValidationError handler to change the 422 format.
  10. How do you test a FastAPI app? TestClient(app) for synchronous tests, or httpx's AsyncClient with ASGITransport for async tests, plus dependency_overrides for the database and auth.

Experienced and senior FastAPI questions (21–30)

  1. 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.
  2. How do you use a database correctly? Async drivers (SQLAlchemy 2.0's asyncio support, asyncpg) inside async def, or synchronous SQLAlchemy inside def endpoints. Open one session per request through a yield dependency, and size connection pools per worker.
  3. How do you stream responses? StreamingResponse over a generator. Release notes show 0.134.0 added streaming JSON Lines and binary data with yield, and 0.135.0 added Server-Sent Events support.
  4. How do WebSockets work? @app.websocket("/ws") with await 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.
  5. 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.
  6. 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.
  7. 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 an asyncio.Semaphore.
  8. 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.
  9. What changed for apps behind a path prefix? 0.146.0 (October 18, 2026) deprecated the root_path parameter of FastAPI(); configure it on the server instead, for example fastapi run --root-path /api/v1.
  10. 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

FormatWhat it usually looks likeHow to prepare
Concept Q&Aasync versus def, Depends, Pydantic validation, response_model, lifespanExplain the event loop rule with one example
Live buildA CRUD API with validation, auth and tests, sometimes as a take-homeBuild one end to end; see REST API interview questions
Code reviewSpot a blocking call in async def, a client per request or a leaky dependencyRead the scenarios above as review prompts
System designServing an ML model or a high-traffic API with FastAPITalk 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