skip to content

FastAPI

FastAPI builds Python APIs on Starlette and Pydantic, with type hints driving validation, injection and OpenAPI docs. It is the default for new Python services and model-serving endpoints.

on this pageshow

explore

questions

138 · 12 sections

In FastAPI, how do you split an application into modules with APIRouter and include_router, and what do prefix, tags, dependencies and responses do?

level: juniorimportance: must knowfreq 62%
basics
~20 s

Each module declares its path operations on an APIRouter, and the main app adds it with app.include_router(). A prefix, tags, dependencies and responses set on the router or at include time apply to every operation in it, inside one OpenAPI schema.

open as a page

In FastAPI, how does a path operation function's parameter declaration decide whether the value comes from the path, the query string or the body?

level: juniorimportance: must knowfreq 75%
basics
~20 s

FastAPI reads each parameter's name, annotation and marker: a name in the path template is a path parameter, a model or other non-scalar type is the body, a plain scalar is a query parameter, and headers or cookies need Header() or Cookie().

open as a page

In FastAPI, when do you include an APIRouter and when do you mount a sub-application with app.mount, and what does a mount not share?

level: middleimportance: must knowfreq 46%
basics
~20 s

Include an APIRouter for parts of one API, sharing the app's schema, docs, handlers and app-wide dependencies. Mount an independent ASGI app with app.mount() when it needs its own docs, handlers and dependencies; the main middleware still wraps it.

open as a page

In FastAPI, how do Query() and Path() inside Annotated add constraints such as ge, le and max_length, and what makes a query parameter required?

level: middleimportance: must knowfreq 60%
basics
~20 s

Write the constraint in a marker inside Annotated, such as Annotated[int, Query(ge=1, le=100)] = 20; FastAPI validates it and answers 422 on violation. A query parameter is required exactly when it has no default, even if its type allows None.

open as a page

In FastAPI, why does GET /users/me return a 422 when /users/{user_id} with user_id: int is declared before it?

level: middleimportance: must knowfreq 60%
basics
~20 s

FastAPI tries routes in registration order and /users/{user_id} matches any single segment, including me; the int annotation is validated only after the route is chosen, so it answers 422 instead of falling through. Declare /users/me first.

open as a page

In FastAPI, what does an endpoint receive from a parameter typed with a Pydantic model, and what happens when the JSON body does not fit the model?

level: juniorimportance: must knowfreq 70%
basics
~20 s

FastAPI reads the body as JSON, validates it against the model and passes a model instance. Malformed JSON, a missing required field or a wrong type gets a 422 before the function runs, so the endpoint only ever sees valid data.

open as a page

In FastAPI, how does a separate output model keep a sign-up endpoint from returning the user's password hash?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Declare an output model without password fields, such as UserOut, as the endpoint's response_model or return type. FastAPI validates the returned data against it and sends only its declared fields, so hashed_password never reaches the JSON.

open as a page

In FastAPI, what JSON body does an endpoint expect with several body parameters, and what does Body(embed=True) change for a single one?

level: middleimportance: must knowfreq 62%
basics
~20 s

With more than one body parameter, FastAPI expects one JSON object keyed by the parameter names, each holding its own value. A single model parameter is the whole body; Body(embed=True) wraps it under its parameter name instead.

open as a page

In FastAPI, how do response_model and a return type annotation differ, and which one wins when a path operation declares both?

level: middleimportance: must knowfreq 60%
basics
~20 s

Both declare the response model FastAPI validates, filters and documents. The return annotation also satisfies type checkers; response_model is a decorator parameter for when the function returns something else. If both are set, response_model wins; response_model=None disables it.

open as a page

In FastAPI, how do you implement a PATCH endpoint that changes only the product fields the client actually sent?

level: middleimportance: should knowfreq 52%
basics
~10 s

Declare an update model whose fields all default to None, then merge only patch.model_dump(exclude_unset=True) into the stored product. Fields the client omitted never appear in that dict, so they keep their stored values.

open as a page

In FastAPI, what does Depends() do with a function, and how does an Annotated alias let several endpoints share it?

level: juniorimportance: must knowfreq 75%
basics
~20 s

fastapi.Depends(func) tells FastAPI to call func for each request, reading func's own parameters as request inputs, and inject its return value. An alias such as Paging = Annotated[dict, Depends(paging)] bundles the type and the Depends so every endpoint reuses one declaration.

open as a page

In FastAPI, how does a dependency written with yield instead of return run setup and cleanup around a request?

level: juniorimportance: must knowfreq 62%
basics
~20 s

FastAPI runs the code before the yield ahead of the endpoint, injects the yielded value, and runs the code after it once the request finishes, by default after the response is sent. Wrap the yield in try/finally.

open as a page

In FastAPI, why does a dependency used by both a sub-dependency and the endpoint run once per request, and what does use_cache=False change?

level: middleimportance: must knowfreq 65%
basics
~20 s

FastAPI keeps a cache for each request, keyed by the dependable callable, so a dependency declared in several places in one request is called once and every consumer receives the same returned object. Depends(f, use_cache=False) makes that declaration call f again.

open as a page

In FastAPI, how do Depends(RateLimiter) and Depends(RateLimiter(limit=10)) differ when RateLimiter is a class with __init__ and __call__?

level: middleimportance: should knowfreq 45%
basics
~10 s

Depends(RateLimiter) makes FastAPI call the class per request, so init's limit becomes a client-supplied query parameter. Depends(RateLimiter(limit=10)) passes a configured instance; FastAPI reads and calls call and never touches init.

open as a page

In FastAPI, how do dependencies=[...] on a path operation decorator, an APIRouter and the FastAPI app differ from a Depends parameter?

level: middleimportance: should knowfreq 45%
basics
~10 s

Dependencies listed in dependencies=[...] run for the request like parameter dependencies, but their return values are discarded. FastAPI runs app-level ones first, then router-level, then decorator-level, then the endpoint's parameter dependencies.

open as a page

In FastAPI, how do you make a sign-up endpoint send a welcome email only after the client has received its response?

level: juniorimportance: must knowfreq 55%
basics
~10 s

Declare a parameter typed BackgroundTasks, call background_tasks.add_task(send_welcome_email, email) and return normally; FastAPI sends the response first, then calls the function with those arguments in the same process.

open as a page

In FastAPI, when should a path operation function be declared with plain def, and when with async def?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Use async def when the function awaits an async library or does no blocking I/O; use plain def when it calls a blocking library, because FastAPI runs def functions on a worker thread. When unsure, def is the safer choice.

open as a page

In FastAPI, when a dependency and the endpoint both add tasks to BackgroundTasks, in what order and on which threads do they run?

level: middleimportance: must knowfreq 50%
basics
~20 s

Both get the same per-request BackgroundTasks, so the tasks run as one list in the order add_task was called, one at a time, after the response: def tasks on a thread-pool thread, async def tasks on the event loop.

open as a page

A FastAPI async def endpoint calls a synchronous SDK, and latency rises on every endpoint served by that worker; why, and how do you fix it?

level: seniorimportance: must knowfreq 60%
basics
~20 s

FastAPI awaits an async def endpoint on the worker's single event loop, so a blocking SDK call there freezes every request on that worker. Declare the endpoint def, wrap the call in run_in_threadpool, or switch to an async client.

open as a page

In FastAPI, why does a CPU-bound image-thumbnail endpoint slow other requests whether it is declared def or async def?

level: middleimportance: should knowfreq 45%
basics
~20 s

CPU work holds CPython's GIL. Inside async def it runs on FastAPI's event loop and freezes every request on that worker; inside def it runs on a worker thread but shares the GIL with the loop, so other requests still slow.

open as a page

In FastAPI, how do you send an error such as 404 from a path operation with HTTPException, and what does the client receive?

level: juniorimportance: must knowfreq 80%
basics
~10 s

Raise fastapi.HTTPException with a status_code, an optional detail and optional headers. FastAPI's default handler answers with that status, those headers and a JSON body {"detail": ...}; the rest of the path operation never runs.

open as a page

In FastAPI 0.143, what does the default 422 validation response body contain, and which request failures produce it?

level: middleimportance: must knowfreq 62%
basics
~20 s

FastAPI 0.143 answers a RequestValidationError with 422 and {"detail": [...]}, one Pydantic 2 error per problem carrying type, loc, msg, input and sometimes ctx. Invalid path, query, header, cookie or body values and malformed JSON all produce it.

open as a page

In FastAPI, when should an uploaded file parameter be bytes and when UploadFile, and what does each hold in memory?

level: middleimportance: must knowfreq 45%
basics
~20 s

Annotated[bytes, File()] hands the endpoint the whole file in memory, which suits small uploads. UploadFile wraps a spooled temporary file that moves to disk past about 1 MB, exposes filename and content_type, and suits large or streamed files.

open as a page

In FastAPI 0.143, what does a path operation give up when it returns a JSONResponse directly instead of plain data?

level: middleimportance: must knowfreq 45%
basics
~20 s

A returned JSONResponse is sent as is: no response_model validation or filtering, no conversion of datetimes or models, no headers or status from a Response parameter, no Pydantic JSON fast path, and docs that may not match the body.

open as a page

In FastAPI, how do you declare form fields with Form(), and what goes wrong when you omit Form() or python-multipart?

level: juniorimportance: should knowfreq 40%
basics
~10 s

Declare each field as Annotated[str, Form()] and install python-multipart. Without Form() a str parameter becomes a query parameter, and without python-multipart FastAPI raises a RuntimeError as soon as the route is declared.

open as a page

In FastAPI, how do you write an @app.middleware("http") function that adds a request-timing header, and which requests does it run for?

level: juniorimportance: must knowfreq 40%
basics
~20 s

Decorate an async function taking request and call_next with @app.middleware("http"), await call_next(request), then set a header such as X-Process-Time on the returned response. It wraps the whole router, so it also runs for 404s, and before any dependency.

open as a page

A FastAPI API called with cookies from a browser app on another origin fails once credentials are sent; how should CORSMiddleware be configured, and why not allow_origins=["*"]?

level: seniorimportance: must knowfreq 45%
basics
~20 s

List the frontend's exact origins in allow_origins, set allow_credentials=True, and name the methods and headers it uses. With credentials on, allow_origins=["*"] makes Starlette echo any Origin back with credentials allowed, so any website could read responses sent with users' cookies.

open as a page

In FastAPI, where do the title, tag groups, summaries and descriptions shown on the /docs page come from?

level: juniorimportance: should knowfreq 40%
basics
~10 s

From FastAPI's generated OpenAPI schema: FastAPI(title, version, description, openapi_tags) sets the API-level text, and each decorator's tags, summary, description, response_description and deprecated set an operation's, defaulting to the function name and docstring.

open as a page

In FastAPI, when middleware is registered with both app.add_middleware and @app.middleware("http"), which runs first, and where do the built-in layers sit?

level: middleimportance: should knowfreq 35%
basics
~20 s

Both styles feed one stack, and each new registration becomes the outermost layer, so the last one added runs first on the request and last on the response. ServerErrorMiddleware wraps all of them; ExceptionMiddleware sits inside them.

open as a page

What do FastAPI's bundled GZipMiddleware, TrustedHostMiddleware and HTTPSRedirectMiddleware each do, and which of their defaults matter when you add them?

level: middleimportance: should knowfreq 25%
basics
~20 s

GZipMiddleware compresses responses for clients accepting gzip, skipping bodies under 500 bytes; TrustedHostMiddleware answers 400 to a Host matching no allowed_hosts entry; HTTPSRedirectMiddleware redirects http and ws requests to https and wss with a 307.

open as a page

In FastAPI, what does an OAuth2PasswordBearer(tokenUrl="token") dependency check on each request, and what does it leave to your code?

level: middleimportance: must knowfreq 72%
basics
~20 s

OAuth2PasswordBearer reads the Authorization header, checks that the scheme is Bearer and returns the rest as a string, answering 401 with WWW-Authenticate: Bearer otherwise. It never validates the token; decoding it and loading the user are your code's job.

open as a page

In a FastAPI app, how does a get_current_user dependency turn a bearer JWT into a user, and where does get_current_active_user fit?

level: middleimportance: must knowfreq 70%
basics
~20 s

get_current_user depends on the OAuth2PasswordBearer scheme, decodes the token with PyJWT's jwt.decode and a fixed algorithms list, reads sub, loads that user and raises 401 on any failure. get_current_active_user depends on it and rejects disabled accounts.

open as a page

In FastAPI, what does Security() add over Depends(), and what does it leave for your own code to do?

level: middleimportance: must knowfreq 40%
basics
~20 s

fastapi.Security declares a dependency exactly as Depends does, plus a scopes list that FastAPI passes down to SecurityScopes and writes into the operation's OpenAPI security. It checks nothing; your dependency must compare those scopes with the token.

open as a page

In FastAPI, how do APIKeyHeader, APIKeyQuery and APIKeyCookie differ, and what does each one hand your endpoint?

level: juniorimportance: should knowfreq 40%
basics
~20 s

All three read one named value from the request (a header, a query parameter or a cookie) and return it as a string. A missing or empty value gets 401, but none of them checks that the key is valid.

open as a page

In FastAPI, what does a token endpoint built on OAuth2PasswordRequestForm accept, and what must it send back?

level: juniorimportance: should knowfreq 55%
basics
~10 s

OAuth2PasswordRequestForm reads form-encoded username and password fields, plus optional scope, grant_type, client_id and client_secret. The endpoint itself must return JSON with access_token and token_type set to bearer.

open as a page

In FastAPI, how do you write a WebSocket endpoint with @app.websocket, and how does it receive, send and notice that the client left?

level: juniorimportance: must knowfreq 40%
basics
~10 s

Decorate an async def with @app.websocket(path), take a websocket: WebSocket parameter, await websocket.accept(), then loop over receive_text() or receive_json() and send_text() or send_json(). When the client closes, the next receive raises WebSocketDisconnect.

open as a page

How do you stream a language model's tokens to a browser as Server-Sent Events from a FastAPI 0.143 path operation?

level: middleimportance: must knowfreq 45%
basics
~20 s

Make the path operation a generator and set response_class=EventSourceResponse from fastapi.sse (0.135+). Each yielded value becomes one event with JSON in its data field; yield ServerSentEvent to set event, id, retry, comment or unencoded raw_data.

open as a page

A FastAPI team reuses its get_current_user dependency, built on OAuth2PasswordBearer, on an @app.websocket endpoint, and every connection fails with a TypeError. Why, and how should the socket authenticate?

level: seniorimportance: must knowfreq 35%
basics
~20 s

The fastapi.security classes take request: Request, which FastAPI injects only on HTTP routes, so on a WebSocket the argument is missing. Use a socket dependency that reads a Query, Cookie or Header value, verifies it, and raises WebSocketException.

open as a page

In FastAPI 0.143, what does a path operation send when it uses yield instead of return and sets no response_class?

level: juniorimportance: should knowfreq 35%
basics
~20 s

Since FastAPI 0.134 it streams JSON Lines: each yielded item is serialized to one JSON line and sent as application/jsonl while the function keeps producing. An AsyncIterable[Item] or Iterable[Item] return type validates and filters every item.

open as a page

In FastAPI 0.143, how does a yielding path operation's output differ under the default response class, EventSourceResponse and StreamingResponse?

level: middleimportance: should knowfreq 28%
basics
~20 s

With no response_class FastAPI sends JSON Lines; with EventSourceResponse it sends Server-Sent Events with JSON data; with StreamingResponse it passes each chunk through untouched, so only the first two validate items against the return type.

open as a page

In FastAPI, how do you test an endpoint with fastapi.testclient.TestClient, sending a JSON body and a request header?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Build TestClient(app) and call it from a plain def test like an httpx client: client.post("/items/", json={...}, headers={"X-Token": "..."}), then assert on response.status_code and response.json(). The app runs in process; no server starts.

open as a page

In a FastAPI test, how do you make an endpoint that depends on get_current_user run as a fixed test user?

level: juniorimportance: must knowfreq 62%
basics
~10 s

Add an entry to app.dependency_overrides keyed by the original get_current_user function, whose value is a callable returning the test user; FastAPI calls it instead on every request, and the test removes the entry afterwards.

open as a page

In FastAPI, what does wrapping TestClient(app) in a with block change for an app whose lifespan loads a model, and what breaks without it?

level: middleimportance: must knowfreq 60%
basics
~10 s

Entering with TestClient(app) runs the lifespan's startup, so the model loads and the yielded dict reaches request.state; leaving runs shutdown. Without the block the lifespan never runs, and reading request.state.model raises AttributeError.

open as a page

In FastAPI, what exactly must the key of app.dependency_overrides be, and why can a registered override silently never apply?

level: middleimportance: must knowfreq 52%
basics
~20 s

The key must be the exact callable given to Depends: the function, class, callable instance or lru_cache wrapper. FastAPI does a plain dict lookup, so an alias, a name or a look-alike never matches and raises no error.

open as a page

In a FastAPI test suite, when do you switch from TestClient to httpx.AsyncClient with ASGITransport, and what must that setup add?

level: middleimportance: should knowfreq 45%
basics
~20 s

Switch when the test must await something itself, such as an async database check. Write an async def test marked @pytest.mark.anyio, await an AsyncClient over ASGITransport(app=...) with a base_url, and run the lifespan through LifespanManager.

open as a page

In a FastAPI app, how does a yield dependency give each request its own database Session, and why is the engine created only once?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Create the engine once per process, write get_session() that yields a Session inside a with block, and alias it as SessionDep = Annotated[Session, Depends(get_session)]. FastAPI calls it once per request and closes the session afterwards.

open as a page

In a FastAPI session dependency, why commit inside the endpoint rather than after the yield, and what happens to uncommitted work when the endpoint raises?

level: middleimportance: must knowfreq 55%
basics
~20 s

Under FastAPI's default request scope, code after yield runs after the response is sent, so a failed commit there still leaves the client with a 200. Commit in the endpoint; if the endpoint raises, closing the session discards uncommitted work.

open as a page

In FastAPI with SQLModel, why should a table model not be the response model, and how do Base, Create, Public and Update models fix it?

level: middleimportance: must knowfreq 45%
basics
~20 s

Returned as the response, a SQLModel table model sends every column and documents id as optional; as a body it lets clients send id. Data models fix it: a shared Base, a Create model for input, a Public model for output and an all-optional Update model.

open as a page

In FastAPI with SQLModel, how do you write a paginated list endpoint and a read-one endpoint that answers 404 for a missing row?

level: juniorimportance: should knowfreq 35%
basics
~10 s

Build select(Book).offset(offset).limit(limit), run it with session.exec(...).all(), and bound limit with Query(le=100). For one row, session.get(Book, book_id) returns None when nothing matches, so raise HTTPException with status 404.

open as a page

In a FastAPI app using SQLModel, what does `table=True` change about a model class, and what is a class without it?

level: juniorimportance: should knowfreq 40%
basics
~20 s

With table=True, a SQLModel class is a table model: a Pydantic model that is also a SQLAlchemy-mapped table with columns, keys and indexes. Without it, the class is a data model, a Pydantic schema for API bodies that never gets a table.

open as a page

In FastAPI 0.143, how does the lifespan parameter run startup and shutdown code, and what happens to on_event handlers?

level: juniorimportance: must knowfreq 40%
basics
~10 s

FastAPI(lifespan=...) takes an @asynccontextmanager function: code before yield runs once before requests are accepted, code after yield runs once at shutdown. App-level on_event handlers are deprecated and stop running once lifespan is set.

open as a page

In FastAPI, why are settings usually injected with Depends(get_settings) where get_settings is wrapped in @lru_cache, and what does each part do?

level: middleimportance: should knowfreq 38%
basics
~10 s

Depends(get_settings) makes settings an injectable dependency that tests can replace through app.dependency_overrides. @lru_cache makes get_settings build Settings once per process, since Depends alone caches only within a single request.

open as a page

In a FastAPI app, how does a dict yielded from the lifespan reach endpoints through request.state, and how does that differ from app.state?

level: middleimportance: should knowfreq 32%
basics
~20 s

The yielded dict is stored as lifespan state, and the server puts a shallow copy of it into each request, where request.state.model reads it. app.state is one object on the application, set by assignment and read through request.app.state.

open as a page

As the lead of a FastAPI inference service, would you create its model, outbound HTTP client and settings at import time, in the lifespan or through an app factory, and why?

level: principalimportance: should knowfreq 30%
basics
~20 s

Heavy or closable resources go in the lifespan: created before yield, handed over as state, closed after it. A create_app(settings) factory lets tests pass their own settings. Import-time globals load for every importer, tests and tools included.

open as a page

A FastAPI app mounts a second FastAPI app with app.mount(), and the mounted app's lifespan never loads its model; why, and how do you fix it?

level: seniorimportance: nice to knowfreq 18%
basics
~20 s

Only the application the server runs receives lifespan events; app.mount() never forwards them, so a mounted app's lifespan does not run. Use an APIRouter with lifespan= and include_router, which merges it, or enter the sub-app's lifespan from the parent's.

open as a page

In FastAPI, how do the `fastapi dev` and `fastapi run` commands differ, and which one belongs in production?

level: juniorimportance: must knowfreq 45%
basics
~10 s

Both start Uvicorn with your app. fastapi dev binds 127.0.0.1 with auto-reload for local work; fastapi run binds 0.0.0.0 without reload and accepts --workers, so fastapi run is the production and container command.

open as a page

What does `fastapi run --workers 4` start for a FastAPI app, and how do its Uvicorn worker processes share the incoming work?

level: middleimportance: must knowfreq 60%
basics
~20 s

A Uvicorn parent process binds the port once and spawns four worker processes; each imports the FastAPI app, runs its own lifespan and accepts connections from the shared socket. The parent supervises and restarts workers but never handles requests.

open as a page

In a FastAPI app that a reverse proxy serves under /api/v1, what does root_path tell the app, and where can you set it?

level: juniorimportance: should knowfreq 30%
basics
~20 s

root_path is the public path prefix a proxy adds in front of the app. Routes stay declared without it; FastAPI uses it for the docs page, the schema's servers entry and generated URLs. Set it with --root-path or FastAPI(root_path=...).

open as a page

When would you start a FastAPI app with `uvicorn` directly, or with Gunicorn and uvicorn-worker's `UvicornWorker`, instead of `fastapi run`?

level: middleimportance: should knowfreq 35%
basics
~20 s

Use fastapi run by default; call uvicorn directly when you need a Uvicorn option the FastAPI CLI does not pass through; use Gunicorn with uvicorn-worker's UvicornWorker only when you want Gunicorn's process manager, settings and hooks.

open as a page

Behind a TLS-terminating proxy, why does a FastAPI app run with fastapi run redirect /items to an http:// URL, and what fixes it?

level: middleimportance: should knowfreq 35%
basics
~10 s

The proxy reaches Uvicorn over plain HTTP, so the request's scheme is http unless Uvicorn trusts the proxy's X-Forwarded-Proto. It trusts only 127.0.0.1 and ::1 by default; list the proxy's address in --forwarded-allow-ips.

open as a page