FastAPI interview cheat sheet
Type-driven APIs: Pydantic, dependency injection, async, auth, testing and deployment
FastAPI interviews check whether you understand what the type hints actually do (parsing, validation, docs), how dependency injection works per request, and when code runs on the event loop vs the threadpool. Senior rounds add auth with JWT, async SQLAlchemy sessions, testing with dependency_overrides and production deployment. Read the 15-minute revision first, then switch to Quiz mode and answer out loud. The runnable snippets are small stdlib models of what FastAPI does internally.
15-minute revision
- FastAPI = Starlette (ASGI routing, requests, middleware, WebSockets) + Pydantic (validation and serialization) + automatic OpenAPI docs at
/docsand/redoc. - ASGI is the async successor of WSGI:
async def app(scope, receive, send). It supports long-lived connections (WebSockets) and many concurrent requests per process. Uvicorn is the usual ASGI server. - Parameter rules: name in the path → path param; simple type (
int,str,bool…) → query param; Pydantic model → JSON body. Lists in the query needQuery(). - Bad input never reaches your code: FastAPI returns 422 with a
detaillist (loc,msg,type) for every failed field. - Use
Annotated[int, Query(ge=1, le=100)]style. Constraints likege,max_lengthandpatternappear in validation and in the OpenAPI schema. - Pydantic v2:
Field(...),@field_validator,@model_validator,model_dump(),model_validate(),ConfigDict(from_attributes=True)(wasorm_mode). response_model(or the return type) filters the output. Use separateUserIn/UserOutmodels so secrets like passwords never leak.raise HTTPException(404, detail=...)for expected errors. Register@app.exception_handler(MyError)to map domain errors to responses in one place.Depends()builds a graph of dependencies per request. The same dependency is cached within a request unlessuse_cache=False.- A dependency with
yieldis setup + teardown (DB session, lock). Code afteryieldruns after the response by default (scope="request"). async defruns on the event loop, so never block it. A plaindefendpoint or dependency runs in a threadpool (AnyIO, 40 threads by default).BackgroundTasksrun after the response, in the same process. Use Celery, RQ or arq for heavy, retryable or cross-process jobs.- Middleware wraps every request; the last added is the outermost. Use
CORSMiddlewarewith explicit origins when credentials are allowed. - Auth:
OAuth2PasswordBearer(tokenUrl="token")readsAuthorization: Bearer <jwt>. Verify the signature andexp, then load the user in a dependency.Security(dep, scopes=[...])adds scopes. - Use
lifespan(an async context manager) for startup and shutdown;@app.on_eventis deprecated. Usepydantic-settingsBaseSettingsfor env config. - Test with
TestClient(built on HTTPX) and swap real dependencies viaapp.dependency_overrides. Deploy withfastapi run/uvicorn --workers N, or one process per container on Kubernetes.
Foundations
What FastAPI is (Starlette + Pydantic)
A thin, type-hint-driven layer on top of Starlette and Pydantic that gives you validation, serialization and OpenAPI docs for free.
- Starlette provides the web part: ASGI app, routing,
Request/Response, middleware, WebSockets, background tasks and the test client. - Pydantic provides the data part: parsing JSON into typed objects, validating it, and turning objects back into JSON. Pydantic v2 has a Rust core (
pydantic-core), so it is fast. - FastAPI reads your function signature once at startup. From the type hints it decides where each value comes from, how to validate it and how to document it.
- The same type hints give you editor autocomplete and type checking, so there is one source of truth for code, validation and docs.
- Install with
pip install "fastapi[standard]". That adds Uvicorn, thefastapiCLI (fastapi devfor reload,fastapi runfor production) and other common extras. - It is a micro-framework in scope: no ORM, no admin, no template system by default. You choose SQLAlchemy, SQLModel, Alembic and so on.
Interview questions
- What is FastAPI and what is it built on?
- What happens when a request hits a FastAPI endpoint?
- Is FastAPI a full-stack framework like Django?
ASGI vs WSGI
WSGI is a synchronous call-and-return interface. ASGI is an async, event-based interface that also handles WebSockets and long-lived connections.
- WSGI (PEP 3333):
app(environ, start_response)returns an iterable body. One request holds one worker thread or process until it finishes. - ASGI:
async def app(scope, receive, send). The server passes ascopedict (type, path, headers) and two async callables to receive and send events. - Because it is async, one process can keep thousands of idle connections open while waiting on I/O. That makes WebSockets, SSE and streaming natural.
- ASGI has three scope types:
http,websocketandlifespan(startup and shutdown events). - Servers: WSGI → Gunicorn, uWSGI. ASGI → Uvicorn, Hypercorn, Granian. Frameworks: WSGI → Flask, classic Django. ASGI → Starlette, FastAPI, Django (ASGI mode), Quart.
- ASGI gives concurrency, not parallelism. CPU-bound work still needs more processes (workers) because of the GIL.
Interview questions
- What is the difference between WSGI and ASGI?
- Why can't Flask (WSGI) do WebSockets natively?
- Does ASGI make CPU-heavy endpoints faster?
Path, query and body parameters
FastAPI decides where each argument comes from by its name and type, then converts and validates it.
- Path params are declared in the route (
/items/{item_id}) and in the signature. They are always required. - Query params are other arguments with simple types. A default value makes them optional; no default makes them required.
- Body: an argument typed as a Pydantic model is read from the JSON body. Several models become keys of one JSON object.
Body(embed=True)wraps a single one. - Other sources need explicit markers:
Header(),Cookie(),Form()(needspython-multipart),File()/UploadFile. - Add rules with
Annotated:Path(ge=1),Query(min_length=3, max_length=50, pattern="^[a-z]+$"),alias,deprecated=True, and descriptions for docs. - Values are converted from strings:
"42"→42,"true"/"1"/"yes"→True. Enums restrict values to a fixed set. - Route order matters: declare
/users/mebefore/users/{user_id}, ormewill be parsed as an id and fail with 422.
Interview questions
- How does FastAPI know if a parameter is path, query or body?
- What happens if a client sends
/items/abcwhenitem_id: int? - How do you make a query parameter required, optional or with a default?
- Why does
/users/mereturn 422 in my app?
Pydantic v2 models & response_model
Pydantic models describe the shape of data in and out. response_model validates and filters what you return.
- A model is a class extending
BaseModelwith typed fields. Defaults make fields optional. Nested models andlist[Model]work naturally. Field()adds constraints and metadata:gt,ge,max_length,pattern,default_factory,alias,description,examples.@field_validator("name")checks or transforms one field.@model_validator(mode="after")checks rules across fields (such asstart < end).- v2 method names:
model_dump()(was.dict()),model_dump_json(),model_validate()(wasparse_obj),model_copy(update=...),model_json_schema(). model_config = ConfigDict(from_attributes=True)lets you build a model from an ORM object (wasorm_mode).extra="forbid"rejects unknown keys.response_model(or a return type annotation) validates the output, drops fields not in the model, and documents the response schema.- Use
response_model_exclude_unset=Trueormodel_dump(exclude_unset=True)for PATCH, so only fields the client actually sent are applied.
Interview questions
- What does
response_modeldo? - Why use separate input and output models?
- Difference between
field_validatorandmodel_validator? - How do you implement PATCH correctly?
Status codes, HTTPException & exception handlers
Set success codes on the decorator, raise HTTPException for expected errors, and map domain exceptions with handlers.
- Set the success code with
status_code=201(orstatus.HTTP_201_CREATED) on the decorator. Use204for delete with no body. raise HTTPException(status_code=404, detail="Item not found")stops the request.detailcan be any JSON-able value;headerscan be added (for exampleWWW-Authenticate).- Validation errors raise
RequestValidationError, which becomes 422 with a list of errors. @app.exception_handler(MyDomainError)turns your own exceptions into responses, so service code does not need to know about HTTP.- To change the format of all HTTP errors, register a handler for Starlette's
HTTPException; it also catches FastAPI's subclass and internal 404/405 errors. - Unhandled exceptions become 500 and are logged; the client sees a generic message.
Interview questions
- Difference between 401 and 403?
- When does FastAPI return 422 and can you change it?
- How do you keep HTTP concerns out of the service layer?
Dependency injection & concurrency
Dependency injection with Depends
Depends(fn) tells FastAPI to call fn first, with its own resolved parameters, and pass the result in.
- A dependency is any callable: a function, an
asyncfunction or a class (its__init__params are resolved). It can declare query params, headers, bodies and other dependencies. - Dependencies form a graph. FastAPI resolves sub-dependencies first, then the parent, then the endpoint.
- Per-request caching: if the same dependency appears several times in one request's graph, it runs once and the value is reused.
Depends(fn, use_cache=False)disables that. - Reuse with type aliases:
CurrentUser = Annotated[User, Depends(get_current_user)], thendef ep(user: CurrentUser). - Attach dependencies for side effects only (auth checks, rate limits) via
dependencies=[Depends(verify_key)]on a route, a router or the whole app. - Dependencies are how you share DB sessions, settings, current user, pagination and permission checks, and how tests swap them via
dependency_overrides.
Interview questions
- What is dependency injection in FastAPI and why use it?
- If two dependencies both depend on
get_db, how many sessions are created? - How do you apply an auth check to every route in a router without adding a parameter?
- Can a class be a dependency?
Dependencies with yield (setup and teardown)
Code before yield is setup, the yielded value is injected, and code after yield is cleanup that always runs.
- Typical use: open a DB session or transaction, acquire a lock or a client,
yieldit, and close it infinally. - Wrap the
yieldintry/except/finally. Exceptions raised in the endpoint or other dependencies are thrown back into the dependency at theyieldpoint. - If you catch an exception after
yield, re-raise it (or raise another one). Swallowing it hides the error: the client gets a 500 with no server log. - Exit code runs in reverse order of setup, so a dependency can still use its sub-dependencies during cleanup.
- By default (
scope="request") the exit code runs after the response is sent. Recent FastAPI versions addDepends(dep, scope="function")to clean up right after the endpoint returns, before the response. - Use
yieldexactly once per dependency. FastAPI wraps it withcontextmanager/asynccontextmanagerinternally.
Interview questions
- How does a
yielddependency work? - What happens if the endpoint raises an exception?
- Can I use the request's DB session inside a background task?
async def vs def (event loop and threadpool)
async def runs on the event loop and must only await non-blocking I/O. Plain def runs in a threadpool, so blocking calls are safe there.
- One Uvicorn worker has one event loop on one thread. If an
async defendpoint calls something blocking (time.sleep,requests.get, a sync DB driver), every request in that worker waits. - A plain
defendpoint or dependency is run withrun_in_threadpool(AnyIO). The default limiter allows 40 threads at a time per process. - Rule of thumb: use
async defwhen youawaitasync libraries (httpx.AsyncClient,asyncpg, async SQLAlchemy). Usedefwhen you call blocking libraries. - Inside
async def, push unavoidable blocking calls out withawait run_in_threadpool(fn, ...)orawait asyncio.to_thread(fn, ...). - CPU-heavy work (image resizing, ML inference) blocks too. Use a
ProcessPoolExecutor, more workers or a task queue. - Running independent awaits in parallel needs
asyncio.gather(or aTaskGroupon Python 3.11+); sequentialawaits do not overlap.
Interview questions
- When should you use
async defvsdefin FastAPI? - Is a
defendpoint slower than anasync defone? - How do you call a blocking library from an async endpoint?
- Your API has p99 latency spikes and even
/healthis slow. What do you check?
Background tasks
BackgroundTasks runs small jobs after the response is sent, inside the same process. Heavy or critical jobs belong in a real task queue.
- Declare
background_tasks: BackgroundTasksin an endpoint or dependency, then callbackground_tasks.add_task(func, *args, **kwargs). - Tasks run after the response is sent, in the order they were added. Sync functions go to the threadpool; async ones run on the loop.
- Good fits: sending a notification email, writing an audit log, invalidating a cache.
- Limits: no retries, no persistence, no scheduling, no visibility. If the process restarts, queued tasks are lost, and they use the same worker's CPU.
- For heavy, long or must-not-lose work, use Celery, RQ, arq, Dramatiq or a cloud queue, with a broker like Redis or RabbitMQ.
Interview questions
- When do FastAPI background tasks run?
- BackgroundTasks vs Celery?
- Design: users upload a video that must be transcoded. How?
Middleware & CORS
Middleware wraps every request and response. CORS middleware tells browsers which other origins may call your API.
- Write HTTP middleware with
@app.middleware("http")andasync def mw(request, call_next). Code beforeawait call_next(request)runs on the way in; code after runs on the way out. - For reusable or performance-sensitive middleware, write a pure ASGI class (
__call__(scope, receive, send)) and add it withapp.add_middleware(Cls, **options). - Order: each
add_middlewarewraps the current stack, so the last added runs first on the request and last on the response. - Built-ins:
CORSMiddleware,GZipMiddleware,TrustedHostMiddleware,HTTPSRedirectMiddleware. - CORS: browsers block cross-origin JS calls unless the server sends
Access-Control-Allow-Origin. Non-simple requests (JSON body, custom headers, PUT/DELETE) first send anOPTIONSpreflight. - With
allow_credentials=True(cookies, auth headers), you must list explicit origins; the docs say["*"]cannot be used for credentialed requests. - Middleware vs dependency: middleware sees every request (logging, request IDs, timing, CORS). Dependencies are per route and know about parameters (auth, DB).
Interview questions
- What is CORS and how do you enable it in FastAPI?
- In what order does middleware run?
- Would you put authentication in middleware or a dependency?
Security
Authentication: OAuth2 password flow & JWT
Log in once to get a signed token, send it as Authorization: Bearer, and verify it in a get_current_user dependency.
OAuth2PasswordBearer(tokenUrl="token")is a dependency that reads theAuthorization: Bearer <token>header and returns the token string, or a 401 if it is missing. It also adds the Authorize button in/docs.- The
/tokenendpoint takesOAuth2PasswordRequestForm(form fieldsusername,password,scope; needspython-multipart), checks the password hash and returns{"access_token": ..., "token_type": "bearer"}. - A JWT is
base64url(header).base64url(payload).signature. The payload is readable by anyone; the signature only proves it was not changed. - Verify signature, algorithm and
expon every request (jwt.decode(token, key, algorithms=["HS256"])). Put the user id insub. Never put secrets in the payload. - Hash passwords with a slow hash (Argon2 or bcrypt). Current FastAPI docs use PyJWT and pwdlib with Argon2 (older tutorials used python-jose and passlib).
- Other schemes:
HTTPBearer,HTTPBasic,APIKeyHeader,APIKeyCookie. Use short-lived access tokens plus refresh tokens; revoke via a denylist or token version.
Interview questions
- How do you implement JWT auth in FastAPI?
- Is the JWT payload encrypted?
- How do you log out or revoke a JWT?
- HS256 vs RS256?
Authorization: security scopes & roles
Authentication says who you are; authorization says what you may do. FastAPI models fine-grained permissions with OAuth2 scopes and Security().
- Declare available scopes on the scheme:
OAuth2PasswordBearer(tokenUrl="token", scopes={"items:read": "Read items", ...}). They appear in the docs' Authorize dialog. - Require scopes with
Security(get_current_user, scopes=["items:write"])instead ofDepends.SecurityisDependsplus a scope list. - The dependency receives
security_scopes: SecurityScopes. It collects the scopes required by the whole chain of dependants, insecurity_scopes.scopesand.scope_str. - Check the token's
scopeclaim against them and return 401 withWWW-Authenticate: Bearer scope="..."when one is missing (403 is also common for “authenticated but not allowed”). - For simple role checks, a parameterised class dependency is clearer:
Depends(RoleChecker(["admin"])). - Object-level checks (“can this user edit this order?”) belong in the service layer or a dependency that loads the resource and compares the owner.
Interview questions
- Difference between
DependsandSecurity? - Authentication vs authorization?
- How would you implement “users can only edit their own posts, admins can edit any”?
Building real applications
APIRouter & project structure
Split endpoints into APIRouters by feature and include them in the app with a prefix, tags and shared dependencies.
router = APIRouter(prefix="/users", tags=["users"], dependencies=[...], responses={404: {...}})groups related routes.app.include_router(router)adds them; options can also be passed there, and routers can include other routers (/api/v1).- Keep endpoints thin: parse input, call a service function, return a schema. Put DB queries in a repository or CRUD module.
- Separate schemas (Pydantic) from models (SQLAlchemy). Keep settings, DB session and security in a
corepackage. - Version APIs with a prefix router (
/api/v1,/api/v2).app.mount("/static", StaticFiles(...))or a sub-app can be mounted for separate concerns. - Structure by feature (
users/,orders/) scales better in big codebases than by file type (all routers together).
Interview questions
- What is
APIRouterused for? - How would you structure a large FastAPI project?
- How do you version a FastAPI API?
Lifespan events & settings (pydantic-settings)
Use a lifespan async context manager for startup/shutdown resources, and a BaseSettings class for typed configuration from env vars.
@asynccontextmanager async def lifespan(app): <startup>; yield; <shutdown>andFastAPI(lifespan=lifespan). It replaces the deprecated@app.on_event("startup").- Startup: create the DB engine, an
httpx.AsyncClient, connect to Redis, load an ML model. Shutdown: dispose and close them. - Store shared objects on
app.state(or yield a dict as lifespan state, read viarequest.state). Lifespan runs once per worker process. pydantic-settings(a separate package in v2):class Settings(BaseSettings)reads fields from environment variables, with types validated, and optionally a.envfile viamodel_config = SettingsConfigDict(env_file=".env").- Expose settings through a dependency wrapped in
@lru_cacheso the file and env are read once, and tests can override it. - Use
SecretStrfor secrets so they are masked in logs and reprs.
Interview questions
- How do you run code on startup and shutdown in FastAPI?
- How do you manage configuration?
- You run 4 workers. How many times does lifespan run?
Databases: async SQLAlchemy 2.0 & sessions per request
Create one async engine per process, one AsyncSession per request via a yield dependency, and use 2.0-style select() queries.
create_async_engine("postgresql+asyncpg://...", pool_size=..., pool_pre_ping=True)once per process (module level or lifespan). It owns the connection pool.SessionLocal = async_sessionmaker(engine, expire_on_commit=False). Aget_sessionyield dependency gives each request its own session and closes it afterwards.- A session is not thread-safe or task-safe. Never share one across requests or concurrent
asyncio.gathercalls. - 2.0 style:
DeclarativeBase,Mapped[int],mapped_column(), andawait session.execute(select(User).where(User.email == e))then.scalars().all()/.scalar_one_or_none().await session.get(User, id)by primary key. - Lazy loading does not work with async (it would need implicit I/O; you get
MissingGreenlet). Eager-load withselectinload()/joinedload(). - Return ORM objects through a schema with
from_attributes=True. Use Alembic for migrations, notcreate_allin production. - Alternatives: SQLModel (Pydantic + SQLAlchemy in one class, by FastAPI's author), Tortoise ORM, or raw
asyncpgfor maximum speed.
Interview questions
- How do you manage DB sessions in FastAPI?
- Why do I get
MissingGreenletwith async SQLAlchemy? - Should endpoints using a sync ORM be
async def? - How do you avoid exhausting database connections at scale?
Testing: TestClient & dependency_overrides
Call the app in-process with TestClient and replace real dependencies (DB, auth, settings) with app.dependency_overrides.
from fastapi.testclient import TestClient;client = TestClient(app);client.get("/items/1"). It is built on HTTPX, runs the app in-process and needs no server.- Tests can be plain
def test_...functions even when endpoints areasync def; TestClient handles the event loop. app.dependency_overrides[get_session] = override_sessionswaps a dependency for the whole app. Clear it after the test (app.dependency_overrides.clear()).- Use
with TestClient(app) as client:to run lifespan startup/shutdown in tests. - For async tests (when the test itself must await things), use
httpx.AsyncClient(transport=ASGITransport(app=app), base_url="http://test")with pytest-anyio or pytest-asyncio. - DB strategy: a test database with each test inside a transaction that is rolled back, or SQLite/testcontainers. Override auth to return a fake user instead of minting tokens.
Interview questions
- How do you test a FastAPI endpoint that uses a database?
- How do you test protected endpoints without real tokens?
- TestClient vs httpx.AsyncClient?
Docs, real-time & production
OpenAPI docs
FastAPI generates an OpenAPI 3.1 schema from your routes and models and serves Swagger UI at /docs and ReDoc at /redoc.
- The schema is at
/openapi.json. It is built lazily from routes, parameters, models,response_model, status codes and security schemes. - Enrich it with
title,version,descriptionon the app, andsummary,description,tags,responses,deprecated=Trueon routes. Docstrings become descriptions. Field(description=..., examples=[...])andmodel_config = {"json_schema_extra": ...}add examples to models.- Hide routes with
include_in_schema=False. Disable or move docs withFastAPI(docs_url=None, redoc_url=None, openapi_url=None)(for example in production). - Clients can be generated from the schema (TypeScript, Kotlin, etc.). Stable
operation_ids give nicer generated method names. - Pydantic v2 can produce separate input and output schemas for the same model, because defaults make fields required in output but optional in input.
Interview questions
- How does FastAPI generate documentation?
- How do you hide or protect the docs in production?
WebSockets
@app.websocket endpoints accept a persistent two-way connection. Broadcasting across workers needs an external pub/sub like Redis.
- Flow:
await websocket.accept(), then loop onreceive_text()/receive_json()andsend_text()/send_json(). CatchWebSocketDisconnectto clean up. - Dependencies,
Query,CookieandHeaderwork in WebSocket endpoints. Browsers cannot set anAuthorizationheader on WebSockets, so tokens usually come via a query param, a cookie or the first message. - To reject, raise
WebSocketException(code=status.WS_1008_POLICY_VIOLATION)or close with a code.HTTPExceptionis not for WebSockets. - A ConnectionManager keeps connected sockets in memory to broadcast. That list is per process: with several workers or pods, use Redis pub/sub or a message broker to fan out.
- Each connection holds a coroutine and memory. Add heartbeats/timeouts, limit message size, and plan load-balancer idle timeouts and sticky sessions.
- For one-way server push (notifications, progress), Server-Sent Events via
StreamingResponseare simpler than WebSockets.
Interview questions
- How do WebSockets work in FastAPI?
- Your chat works with 1 worker but messages get lost with 4. Why?
- How do you authenticate a WebSocket?
Deployment: Uvicorn, workers & Docker
Run Uvicorn with several worker processes on a VM, or one Uvicorn process per container and let Kubernetes replicate it.
- Dev:
fastapi dev main.py(auto-reload). Prod:fastapi run main.py --workers 4oruvicorn main:app --host 0.0.0.0 --port 8000 --workers 4. - Each worker is a separate process with its own event loop, memory, lifespan and DB pool. A common start is about one worker per CPU core, then load test.
- Gunicorn as process manager:
gunicorn main:app -w 4 -k uvicorn_worker.UvicornWorker. The olduvicorn.workersmodule is deprecated in favour of theuvicorn-workerpackage; Uvicorn's own--workersnow also restarts dead workers. - On Kubernetes/ECS, run one Uvicorn process per container and scale with replicas; the orchestrator already does restarts, health checks and load balancing.
- Behind a proxy (Nginx, ALB, Traefik) terminate TLS there and run Uvicorn with
--proxy-headers(and--forwarded-allow-ips) so client IP and scheme are correct. Setroot_pathif served under a path prefix. - Docker: start from
python:3.x-slim, copy and install requirements first for layer caching, then copy code; use exec-formCMDso signals reach Uvicorn for graceful shutdown. The oldtiangolo/uvicorn-gunicorn-fastapiimage is deprecated.
Interview questions
- How do you deploy FastAPI in production?
- How many workers should you run?
- Why use Gunicorn with FastAPI if Uvicorn already has
--workers?
Performance & FastAPI vs Flask vs Django
FastAPI is fast for I/O-bound APIs when the whole stack is async. Pick Django for batteries-included apps and Flask for simple sync services.
- Speed comes from ASGI + async I/O (Uvicorn with uvloop/httptools) and Pydantic v2's Rust core. Most real latency still comes from the database and network calls.
- Return Pydantic models or use a
response_modelso serialization is done by Pydantic. Avoid building huge dicts by hand and serializing twice. - Use connection pools, async clients created once in lifespan (
httpx.AsyncClient), caching (Redis), pagination, andGZipMiddlewarefor large JSON. - Profile before tuning: blocking calls in
async def, N+1 queries, threadpool exhaustion and too-small DB pools are the usual problems. - Stream large responses with
StreamingResponseand files withFileResponseinstead of loading them into memory. - Python limits: the GIL limits CPU parallelism per process. Scale with processes/pods and offload CPU work.
Interview questions
- FastAPI vs Flask vs Django: which would you choose?
- Why is FastAPI considered fast?
- Your FastAPI service is slow under load. How do you investigate?
- Can Django do what FastAPI does now that it supports async?