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 pageshowhide
explore
- Path Operations & Routing12 questions
- Typed Endpoint Parameters6 questions
- Routers & Mounted Apps6 questions
- Payload Schemas11 questions
- JSON Body Binding5 questions
- Response Model Filtering6 questions
- Depends Wiring11 questions
- Sub-Dependency Reuse6 questions
- Yield Teardown & Scopes5 questions
- Thread Pool & Loop12 questions
- Blocking Work Offload6 questions
- Post-Response Tasks6 questions
- HTTP Inputs & Outputs16 questions
- Form Fields & UploadFile5 questions
- Custom Response Types5 questions
- Error Handlers & 422 Bodies6 questions
- Docs & ASGI Stack12 questions
- OpenAPI Schema Output6 questions
- CORS & Custom Middleware6 questions
- Security Dependencies16 questions
- OAuth2 Password Bearer5 questions
- Scope Checks6 questions
- API Key & HTTP Schemes5 questions
- Live Data Channels11 questions
- JSON Lines & SSE5 questions
- WebSocket Endpoints6 questions
- App Test Tooling11 questions
- TestClient & AsyncClient5 questions
- Swapping Dependencies6 questions
- Data Layer Wiring11 questions
- Session per Request5 questions
- SQLModel Table Models6 questions
- Lifespan, State & Settings5 questions
- Hosting & Launch10 questions
- CLI, Workers & Containers5 questions
- Reverse Proxy Setup5 questions
questions
138 · 12 sectionsIn FastAPI, how do you split an application into modules with APIRouter and include_router, and what do prefix, tags, dependencies and responses do?
basics
~20 sEach 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.
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?
basics
~20 sFastAPI 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().
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?
basics
~20 sInclude 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.
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?
basics
~20 sWrite 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.
In FastAPI, why does GET /users/me return a 422 when /users/{user_id} with user_id: int is declared before it?
basics
~20 sFastAPI 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.
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?
basics
~20 sFastAPI 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.
In FastAPI, how does a separate output model keep a sign-up endpoint from returning the user's password hash?
basics
~20 sDeclare 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.
In FastAPI, what JSON body does an endpoint expect with several body parameters, and what does Body(embed=True) change for a single one?
basics
~20 sWith 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.
In FastAPI, how do response_model and a return type annotation differ, and which one wins when a path operation declares both?
basics
~20 sBoth 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.
In FastAPI, how do you implement a PATCH endpoint that changes only the product fields the client actually sent?
basics
~10 sDeclare 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.
In FastAPI, what does Depends() do with a function, and how does an Annotated alias let several endpoints share it?
basics
~20 sfastapi.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.
In FastAPI, how does a dependency written with yield instead of return run setup and cleanup around a request?
basics
~20 sFastAPI 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.
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?
basics
~20 sFastAPI 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.
In FastAPI, how do Depends(RateLimiter) and Depends(RateLimiter(limit=10)) differ when RateLimiter is a class with __init__ and __call__?
basics
~10 sDepends(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.
In FastAPI, how do dependencies=[...] on a path operation decorator, an APIRouter and the FastAPI app differ from a Depends parameter?
basics
~10 sDependencies 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.
In FastAPI, how do you make a sign-up endpoint send a welcome email only after the client has received its response?
basics
~10 sDeclare 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.
In FastAPI, when should a path operation function be declared with plain def, and when with async def?
basics
~20 sUse 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.
In FastAPI, when a dependency and the endpoint both add tasks to BackgroundTasks, in what order and on which threads do they run?
basics
~20 sBoth 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.
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?
basics
~20 sFastAPI 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.
In FastAPI, why does a CPU-bound image-thumbnail endpoint slow other requests whether it is declared def or async def?
basics
~20 sCPU 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.
In FastAPI, how do you send an error such as 404 from a path operation with HTTPException, and what does the client receive?
basics
~10 sRaise 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.
In FastAPI 0.143, what does the default 422 validation response body contain, and which request failures produce it?
basics
~20 sFastAPI 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.
In FastAPI, when should an uploaded file parameter be bytes and when UploadFile, and what does each hold in memory?
basics
~20 sAnnotated[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.
In FastAPI 0.143, what does a path operation give up when it returns a JSONResponse directly instead of plain data?
basics
~20 sA 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.
In FastAPI, how do you declare form fields with Form(), and what goes wrong when you omit Form() or python-multipart?
basics
~10 sDeclare 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.
In FastAPI, how do you write an @app.middleware("http") function that adds a request-timing header, and which requests does it run for?
basics
~20 sDecorate 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.
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=["*"]?
basics
~20 sList 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.
In FastAPI, where do the title, tag groups, summaries and descriptions shown on the /docs page come from?
basics
~10 sFrom 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.
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?
basics
~20 sBoth 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.
What do FastAPI's bundled GZipMiddleware, TrustedHostMiddleware and HTTPSRedirectMiddleware each do, and which of their defaults matter when you add them?
basics
~20 sGZipMiddleware 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.
In FastAPI, what does an OAuth2PasswordBearer(tokenUrl="token") dependency check on each request, and what does it leave to your code?
basics
~20 sOAuth2PasswordBearer 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.
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?
basics
~20 sget_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.
In FastAPI, what does Security() add over Depends(), and what does it leave for your own code to do?
basics
~20 sfastapi.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.
In FastAPI, how do APIKeyHeader, APIKeyQuery and APIKeyCookie differ, and what does each one hand your endpoint?
basics
~20 sAll 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.
In FastAPI, what does a token endpoint built on OAuth2PasswordRequestForm accept, and what must it send back?
basics
~10 sOAuth2PasswordRequestForm 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.
In FastAPI, how do you write a WebSocket endpoint with @app.websocket, and how does it receive, send and notice that the client left?
basics
~10 sDecorate 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.
How do you stream a language model's tokens to a browser as Server-Sent Events from a FastAPI 0.143 path operation?
basics
~20 sMake 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.
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?
basics
~20 sThe 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.
In FastAPI 0.143, what does a path operation send when it uses yield instead of return and sets no response_class?
basics
~20 sSince 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.
In FastAPI 0.143, how does a yielding path operation's output differ under the default response class, EventSourceResponse and StreamingResponse?
basics
~20 sWith 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.
In FastAPI, how do you test an endpoint with fastapi.testclient.TestClient, sending a JSON body and a request header?
basics
~10 sBuild 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.
In a FastAPI test, how do you make an endpoint that depends on get_current_user run as a fixed test user?
basics
~10 sAdd 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.
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?
basics
~10 sEntering 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.
In FastAPI, what exactly must the key of app.dependency_overrides be, and why can a registered override silently never apply?
basics
~20 sThe 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.
In a FastAPI test suite, when do you switch from TestClient to httpx.AsyncClient with ASGITransport, and what must that setup add?
basics
~20 sSwitch 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.
In a FastAPI app, how does a yield dependency give each request its own database Session, and why is the engine created only once?
basics
~20 sCreate 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.
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?
basics
~20 sUnder 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.
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?
basics
~20 sReturned 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.
In FastAPI with SQLModel, how do you write a paginated list endpoint and a read-one endpoint that answers 404 for a missing row?
basics
~10 sBuild 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.
In a FastAPI app using SQLModel, what does `table=True` change about a model class, and what is a class without it?
basics
~20 sWith 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.
In FastAPI 0.143, how does the lifespan parameter run startup and shutdown code, and what happens to on_event handlers?
basics
~10 sFastAPI(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.
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?
basics
~10 sDepends(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.
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?
basics
~20 sThe 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.
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?
basics
~20 sHeavy 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.
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?
basics
~20 sOnly 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.
In FastAPI, how do the `fastapi dev` and `fastapi run` commands differ, and which one belongs in production?
basics
~10 sBoth 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.
What does `fastapi run --workers 4` start for a FastAPI app, and how do its Uvicorn worker processes share the incoming work?
basics
~20 sA 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.
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?
basics
~20 sroot_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=...).
When would you start a FastAPI app with `uvicorn` directly, or with Gunicorn and uvicorn-worker's `UvicornWorker`, instead of `fastapi run`?
basics
~20 sUse 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.
Behind a TLS-terminating proxy, why does a FastAPI app run with fastapi run redirect /items to an http:// URL, and what fixes it?
basics
~10 sThe 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.