Appearance
3.14.3 — Routes, Parameters & Responses
Here is a whole endpoint for a shop's order service.
python
@app.get("/orders/{order_id}")
async def get_order(order_id: Annotated[int, Path(ge=1)]) -> OrderOut:
...From those three lines, FastAPI knows that order_id comes from the URL, that it must be a whole number of at least 1, that "abc" and "0" must be rejected with a precise error, which fields to put in the response and which to leave out, and how to describe all of it in interactive documentation. You wrote no parsing code, no validation code and no documentation. This page shows exactly how FastAPI reads that information out of an ordinary Python function, covers every place a parameter can come from, explains how responses are filtered and shaped, and ends with the most important performance fact about FastAPI: why def and async def endpoints run in completely different places.
All the examples belong to one small shop API. Here are its models and its fake database, a dict, so every example can run on its own.
python
from decimal import Decimal
from enum import StrEnum
from typing import Annotated
from fastapi import FastAPI, Path, Query, Header, Cookie, HTTPException, status, Form, UploadFile
from pydantic import BaseModel, EmailStr, Field
app = FastAPI(title="Shop API", version="1.4.0")
class OrderStatus(StrEnum):
PENDING = "pending"
PAID = "paid"
SHIPPED = "shipped"
class OrderOut(BaseModel): # what clients are allowed to see
id: int
status: OrderStatus
total: Decimal
class OrderLineIn(BaseModel):
sku: str
quantity: Annotated[int, Field(ge=1, le=100)]
class OrderIn(BaseModel): # what clients are allowed to send
customer_email: EmailStr
lines: list[OrderLineIn] = Field(min_length=1)
ORDERS = {
1: {"id": 1, "customer_email": "asha@example.com", "status": "paid",
"total": Decimal("900.00"), "internal_notes": "VIP customer"},
2: {"id": 2, "customer_email": "ravi@example.com", "status": "pending",
"total": Decimal("40.00"), "internal_notes": ""},
}1. Registering a route
@app.get(path) is a registration decorator, exactly the pattern built by hand in 3.13.5. It records your function in the app's routing table and returns it unchanged. There is one decorator per HTTP method: get, post, put, patch, delete, options and head. The function is called a path operation function, FastAPI's name for an endpoint.
You run the app with a server.
text
$ uvicorn shop.main:app --reload # or: fastapi dev shop/main.py
INFO: Uvicorn running on http://127.0.0.1:8000shop.main:app means "import the module shop.main and use its variable app". --reload restarts the server whenever a file changes, for development only.
What happens when the decorator runs
The important work happens once, at import time, when @app.get runs. FastAPI inspects your function with the two tools from 3.13.4 and 3.13.12: inspect.signature for the parameters and their defaults, and the type hints, including every Annotated extra. From those it builds a plan, which it calls a dependant, that says where each parameter comes from and how to validate it. It also builds one Pydantic validator for all of them. On every request, it only runs that plan.
You can look at the plan.
python
from fastapi.routing import APIRoute
route = next(r for r in app.routes if isinstance(r, APIRoute)
and r.path == "/orders" and "POST" in r.methods)
plan = route.dependant
print("header:", [p.name for p in plan.header_params],
"cookie:", [p.name for p in plan.cookie_params],
"body:", [p.name for p in plan.body_params])text
header: ['idempotency_key'] cookie: ['session_id'] body: ['order']dependant is an internal attribute, not something to use in real code, but it proves the point: FastAPI decided where every parameter comes from before any request arrived.
2. Where each parameter comes from
FastAPI applies three rules, in order, to each parameter of your function.
- If its name appears in the path template, such as
{order_id}, it is a path parameter. - If its type is a Pydantic model, it is read from the request body.
- Otherwise, if its type is a simple type such as
int,str,bool, an enum, or a list of those, it is a query parameter.
You can override the rules with markers inside Annotated: Path(), Query(), Body(), Header(), Cookie(), Form() and File(). Each marker can also carry validation rules, using the same ge, le, min_length and pattern options as Pydantic's Field (3.14.2).
Path parameters
python
@app.get("/orders/{order_id}")
async def get_order(order_id: Annotated[int, Path(ge=1)]) -> OrderOut: # (1)
if order_id not in ORDERS:
raise HTTPException(status_code=404, detail=f"order {order_id} not found") # (2)
return ORDERS[order_id] # (3)text
$ curl localhost:8000/orders/1
{"id":1,"status":"paid","total":"900.00"}
$ curl localhost:8000/orders/0
{"detail":[{"type":"greater_than_equal","loc":["path","order_id"],"msg":"Input should be greater than or equal to 1","input":"0","ctx":{"ge":1}}]}
$ curl localhost:8000/orders/99
{"detail":"order 99 not found"}(1)The name matches{order_id}, so it comes from the path. The text from the URL is converted to anintand checked againstge=1. A bad value gets a 422 listing exactly what failed, with"loc": ["path", "order_id"].(2)RaisingHTTPExceptionstops the request and returns that status code with a JSONdetail. 3.14.5 covers error handling fully.(3)We return a plain dict from the fake database, which containscustomer_emailandinternal_notes. The response shows neither. Section 4 explains why.
Route order matters
Routes are matched in the order they were registered, and the first match wins. Suppose you also want /orders/latest.
python
@app.get("/orders/latest") # (1) must come first
async def latest_order() -> OrderOut:
return ORDERS[max(ORDERS)]
@app.get("/orders/{order_id}")
async def get_order(order_id: Annotated[int, Path(ge=1)]) -> OrderOut:
...(1)If this route were registered after/orders/{order_id}, a request for/orders/latestwould match the parameter route first, try to convert"latest"to an integer, and fail with a 422. Fixed paths go before parameter paths.
Query parameters
Anything after the ? in a URL is the query string: /orders?status=paid&page=2. Simple-typed parameters that are not in the path come from there.
python
@app.get("/orders")
async def list_orders(
status_filter: Annotated[OrderStatus | None, Query(alias="status")] = None, # (1)
page: Annotated[int, Query(ge=1)] = 1, # (2)
page_size: Annotated[int, Query(ge=1, le=100)] = 20, # (3)
tag: Annotated[list[str], Query()] = [], # (4)
) -> list[OrderOut]:
rows = [o for o in ORDERS.values() if status_filter is None or o["status"] == status_filter]
start = (page - 1) * page_size
return rows[start:start + page_size]text
$ curl "localhost:8000/orders?status=paid&page_size=5"
[{"id":1,"status":"paid","total":"900.00"}]
$ curl "localhost:8000/orders?status=lost"
{"detail":[{"type":"enum","loc":["query","status"],"msg":"Input should be 'pending', 'paid' or 'shipped'","input":"lost","ctx":{"expected":"'pending', 'paid' or 'shipped'"}}]}
$ curl "localhost:8000/orders?page_size=500"
{"detail":[{"type":"less_than_equal","loc":["query","page_size"],"msg":"Input should be less than or equal to 100","input":"500","ctx":{"le":100}}]}(1)An optional filter. Typing it as theOrderStatusenum (3.13.8) means only the three real statuses are accepted, and the documentation shows them as a drop-down.alias="status"lets the URL usestatuswhile the Python name avoids clashing with FastAPI'sstatusmodule.(2)A default makes a query parameter optional. A parameter without a default is required.(3)The upper limit protects your database. Without it, a client could ask for ten million rows in one request.(4)A list type accepts repeated keys:?tag=gift&tag=urgentgives["gift", "urgent"]. List query parameters need the explicitQuery()marker, or FastAPI would expect them in the body.
Notice that [] as a default is safe here. FastAPI copies defaults for each request, so the mutable default trap from 3.13.4 does not apply.
Request bodies
A parameter typed as a Pydantic model is read from the JSON body.
python
@app.post("/orders", status_code=status.HTTP_201_CREATED) # (1)
async def create_order(
order: OrderIn, # (2)
idempotency_key: Annotated[str | None, Header()] = None, # (3)
session_id: Annotated[str | None, Cookie()] = None, # (4)
) -> OrderOut:
new_id = max(ORDERS) + 1
ORDERS[new_id] = {"id": new_id, "customer_email": order.customer_email,
"status": "pending", "total": Decimal("0"), "internal_notes": ""}
return ORDERS[new_id]text
$ curl -X POST localhost:8000/orders -H "Idempotency-Key: abc-123" \
-d '{"customer_email": "meera@example.com", "lines": [{"sku": "mug", "quantity": 2}]}'
{"id":3,"status":"pending","total":"0"} ← status 201
$ curl -X POST localhost:8000/orders -d '{"customer_email": "bad", "lines": []}'
{"detail":[{"type":"value_error","loc":["body","customer_email"],"msg":"value is not a valid email address: An email address must have an @-sign.", …},
{"type":"too_short","loc":["body","lines"],"msg":"List should have at least 1 item after validation, not 0", …}]}(1)status_code=201is the correct response to "a new resource was created".fastapi.statusgives readable names for every code.(2)The whole body is validated by Pydantic, including nested lines, and every error is reported at once, each with alocstarting"body".(3)Header()reads a request header. FastAPI converts the Python nameidempotency_keyto the header nameidempotency-key, because HTTP headers use dashes and Python names cannot. Header names are case-insensitive. An idempotency key lets a client safely retry a "create order" request after a timeout without creating two orders (3.13.5 mentioned why).(4)Cookie()reads a cookie by name.
If an endpoint takes two model parameters, FastAPI expects a JSON object with one key per parameter name. To force that wrapping for a single model too, use Body(embed=True).
Forms and files
HTML forms and file uploads do not send JSON. They send form data. Form() and UploadFile read it. They need the python-multipart package installed.
python
@app.post("/support/messages")
async def contact_support(
email: Annotated[str, Form()],
message: Annotated[str, Form()],
screenshot: UploadFile | None = None, # (1)
):
return {"from": email, "chars": len(message),
"file": screenshot.filename if screenshot else None}text
$ curl -X POST localhost:8000/support/messages \
-F email=a@b.co -F "message=Where is my order?" -F screenshot=@screen.png
{"from":"a@b.co","chars":18,"file":"screen.png"}(1)UploadFiledoes not load the whole file into memory. Small files are kept in memory, and larger ones are written to a temporary file on disk. 3.14.8 covers uploads in depth.
The raw request
When you need something FastAPI does not model, such as the client's IP address or the exact raw body for checking a payment provider's signature, declare a parameter of type Request. FastAPI passes in Starlette's request object. Use this sparingly, because anything read this way is not validated and does not appear in the documentation.
3. The interactive documentation
Because FastAPI knows every parameter, type and constraint, it generates an OpenAPI document, a standard JSON description of an HTTP API, at /openapi.json. Two pages render it.
/docsshows Swagger UI, where you can read every endpoint and send real requests from the browser./redocshows the same information as a clean reference page.
Here is the entry FastAPI generated for the page_size parameter.
python
print(app.openapi()["paths"]["/orders"]["get"]["parameters"][2])text
{'name': 'page_size', 'in': 'query', 'required': False, 'schema': {'type': 'integer', 'maximum': 100, 'minimum': 1, 'default': 20, 'title': 'Page Size'}}The le=100 you wrote is enforced on every request and published to every client team, from the same line of code. Front-end and mobile teams often generate their client code directly from this document. Add summary=, description=, tags= and a docstring to an endpoint, and they appear in the documentation too. In production you can turn the pages off with FastAPI(docs_url=None, redoc_url=None) if the API is not public.
4. Responses: shaping and filtering what leaves the server
The response model is a security boundary
Go back to get_order. The fake database row contains customer_email and internal_notes, yet the response contained only id, status and total. That is because the function's return type is OrderOut. FastAPI uses the return annotation as the response model. Before sending anything, it validates the returned value against OrderOut and serialises only the fields OrderOut declares.
This matters more than it looks. The most common way APIs leak data is returning a database object directly and forgetting that it has a password_hash or internal_notes column. With a response model, a field must be listed explicitly to leave the server. New database columns stay private until someone deliberately adds them to the output model.
The usual pattern is three models per resource:
- an input model, such as
OrderIn, with only the fields a client may send; - an output model, such as
OrderOut, with only the fields a client may see; - the database model, with everything (3.14.6).
If you must return something other than the declared type, put the model in the decorator instead: @app.get(..., response_model=OrderOut). Options such as response_model_exclude_none=True tune the output.
Response classes
By default FastAPI turns your return value into JSON. To send something else, return a response object, or set response_class on the decorator.
python
from fastapi.responses import PlainTextResponse, RedirectResponse
@app.get("/health", response_class=PlainTextResponse)
def health() -> str:
return "ok" # (1)
@app.get("/old-orders/{order_id}")
def old_order_url(order_id: int):
return RedirectResponse(f"/orders/{order_id}", status_code=301) # (2)(1)The body is the plain textok, not the JSON string"ok". Load balancers often expect exactly that for health checks.(2)A permanent redirect from an old URL.
Other response classes include HTMLResponse, FileResponse for sending a file from disk efficiently, and StreamingResponse for sending a body piece by piece (3.14.8). Returning a response object directly skips the response model, so you take responsibility for what it contains.
5. Organising a real service: APIRouter
Putting every endpoint on one app in one file stops working after a dozen endpoints. An APIRouter is a mini-app that holds a group of related routes. The main app includes it.
python
# shop/orders/routes.py
from fastapi import APIRouter
router = APIRouter(prefix="/orders", tags=["orders"]) # (1)
@router.get("/{order_id}") # (2)
async def get_order(order_id: int) -> OrderOut:
...python
# shop/main.py
from fastapi import FastAPI
from shop.orders.routes import router as orders_router
from shop.payments.routes import router as payments_router
app = FastAPI(title="Shop API")
app.include_router(orders_router) # (3)
app.include_router(payments_router)(1)Every route in this router gets the/ordersprefix and theorderstag, which groups them in the documentation.(2)So this path is really/orders/{order_id}.(3)Including a router copies its routes into the app.
A common layout puts each area of the business in its own package: shop/orders/ holding routes.py, schemas.py for the Pydantic models, service.py for business logic and repository.py for database access. The route functions stay thin. They translate HTTP into a call to the service and back. Routers can also carry shared dependencies, such as "every route here requires a logged-in user" (3.14.4).
6. def or async def: the most important performance fact
FastAPI accepts both kinds of endpoint function, and it runs them in different places.
- An
async defendpoint is awaited on the event loop (3.13.15). It must never block, because while it runs, nothing else on that worker can. - A plain
defendpoint is sent to a thread pool by Starlette, using a helper from theanyiolibrary. The event loop stays free while the function blocks in its thread. That pool allows 40 threads at once by default.
Here is the difference measured. Three endpoints each take 0.5 seconds, the way a slow database call would.
python
import asyncio
import time
@app.get("/def-blocking")
def def_blocking(): # (1) plain def, blocking call
time.sleep(0.5)
return {"ok": True}
@app.get("/async-blocking")
async def async_blocking(): # (2) async def, blocking call: the bug
time.sleep(0.5)
return {"ok": True}
@app.get("/async-awaiting")
async def async_awaiting(): # (3) async def, awaiting call
await asyncio.sleep(0.5)
return {"ok": True}Twenty clients called each endpoint at the same time, against one Uvicorn worker.
text
/async-awaiting 20 requests: 0.6s
/def-blocking 20 requests: 0.6s
/async-blocking 20 requests: 10.1s
/def-blocking 80 requests: 1.3s(1)defplus blocking: fine. Twenty threads waited in parallel, so twenty requests took about as long as one.(2)async defplus blocking: a disaster.time.sleepfroze the event loop, so the requests ran one after another: 20 × 0.5 = 10 seconds. While this happens, every other endpoint on the worker is frozen too, including the health check, so a load balancer may decide the whole server is dead.(3)async defplusawait: ideal. Twenty waits overlapped on one thread, with no threads needed.
The last line shows the thread pool's limit. Eighty blocking requests need two rounds of 40 threads, so they took twice as long.
The rule is simple, and it is the single most valuable thing to know about FastAPI performance.
- If the endpoint uses async libraries for its waiting, such as an async database driver or
httpx.AsyncClient, writeasync defandawaitthem. - If it uses blocking libraries, such as
requests, a synchronous database driver or a slow file operation, write plaindef, and let FastAPI run it in the thread pool. - Never call a blocking library inside
async def. If you must, wrap that one call withawait asyncio.to_thread(...)or Starlette'srun_in_threadpool.
CPU-heavy work belongs in neither place. A long computation in def holds the GIL and slows every thread (3.13.13), and in async def it freezes the loop. Send it to a process pool or a job queue (3.13.14).
What the interviewer will push on
"How does FastAPI decide whether a parameter is a path, query or body parameter?" Name in the path template means path. Pydantic model type means body. Simple types mean query. Annotated markers like Query(), Header() or Body() override the rules. The tell of depth: this is decided once at start-up from inspect.signature and the type hints, not on every request.
"What does response_model do, and why does it matter for security?" It validates and filters the return value so only declared fields are sent. That prevents leaking internal columns such as password hashes. Mention separate input and output models, and that returning a Response object directly bypasses the filtering.
"def or async def for an endpoint?" async def only when everything it waits on is awaited with async libraries. def for blocking libraries, because FastAPI runs it in a thread pool of 40 by default. Calling blocking code inside async def freezes the whole worker. Being able to give the measured numbers, or explain them, is what separates candidates.
"Why might /orders/latest return a 422?" It was registered after /orders/{order_id}, so the parameter route matched first and failed to parse "latest" as an integer. Routes match in registration order.
"How would you paginate a list endpoint?" Validated query parameters with an upper bound on page size, such as Query(ge=1, le=100). For large or fast-changing tables, mention cursor-based pagination, which uses the last seen ID instead of an offset, because big offsets are slow and skip or repeat rows when data changes.
Something to volunteer that nobody asks for: the 422 response lists every invalid field with its location, so front-end teams can highlight all errors from one request. And the constraints you write, like le=100, appear in /openapi.json, so the validation and the documentation can never drift apart.
Recall
@app.get(path)registers a path operation function. At import time FastAPI readsinspect.signatureand the type hints and builds a dependant plan. Per request, it only runs the plan.- Name in the path → path parameter. Pydantic model → body. Simple type → query string. Override with
Path(),Query(),Body(),Header(),Cookie(),Form(),File(), each with constraints.Headerconverts_to-. Defaults make parameters optional.list[str]query parameters needQuery(). - Invalid input → 422 listing each error's
loc.HTTPExceptionfor 404 and friends.status_code=201for creation. - Routes match in registration order, so fixed paths go first.
- The return annotation is the response model: only declared fields leave the server. Use separate input, output and database models. Returning a
Responsebypasses it. /docs,/redocand/openapi.jsonare generated from the same code.APIRouter(prefix=..., tags=...)plusinclude_routerorganise a service.async defruns on the event loop and must not block.defruns in a 40-thread pool. Blocking insideasync defserialises every request on the worker.
Self-test: Without running it, say where each parameter of def f(order_id: int, page: int = 1, body: OrderIn = ...) on /orders/{order_id} comes from. Why does a response model protect internal_notes? Why did twenty blocking async def requests take ten seconds while twenty blocking def requests took 0.6?
Quiz Bank
FoundationalWhat is the difference between a 404 and a 422 in a FastAPI service?
A 422 Unprocessable Content means the request reached a matching route, but its data failed validation before your function ran, for example a path parameter that is not an integer, a missing required field, or a value outside its constraints. FastAPI produces it automatically, with a list of errors. A 404 Not Found means either that no route matched the path, which Starlette produces, or that your own code decided the requested resource does not exist and raised HTTPException(404). The first is about the shape of the request, the second about whether the thing exists.
AppliedAn endpoint returns a SQLAlchemy User object and the response suddenly contains password_hash after a migration added the column. How do you prevent this class of bug?
Never let the database model define the API output. Declare an explicit output model, such as UserOut with id, email and name, as the endpoint's return annotation or response_model, with from_attributes=True so it can read attributes from the ORM object. FastAPI then serialises only the declared fields, so new columns stay private until someone deliberately adds them to UserOut. Back it up with a review rule that endpoints must not return Response objects built from raw ORM data, and with a check that response schemas in /openapi.json contain no sensitive field names.
InterviewAn async def endpoint calls requests.get() to fetch a shipping quote. What happens under load, and how do you fix it?
requests.get is a blocking call, so while it waits for the network the event loop thread is stuck, and no other request on that worker can make progress, including health checks. Under load, requests are effectively served one at a time, latency multiplies, and timeouts cascade. There are two fixes. Switch to an async client, httpx.AsyncClient, created once and shared, and await client.get(...) with a timeout. Or keep requests but make the endpoint a plain def, so FastAPI runs it in its thread pool, accepting the 40-thread default limit or raising it. Wrapping only the call in await asyncio.to_thread(requests.get, ...) also works as a quick fix.
StaffYou are defining API conventions for twenty teams building FastAPI services. What would you standardise at the routing and schema level?
One router per business area with consistent prefixes and tags. Separate input, output and database models, with output models always declared. Plural resource nouns with HTTP methods carrying the verb, 201 for creation and 204 for deletes. A shared error body format built from the 422 shape plus domain error codes. Pagination with bounded page_size, or cursors for large tables, and consistent query parameter names. Idempotency keys as a header on every non-idempotent POST. camelCase or snake_case chosen once, using Pydantic alias generators. Explicit def versus async def guidance tied to the libraries each service uses, with a lint check that bans known blocking calls inside async def. Published OpenAPI documents checked in CI for breaking changes, so a removed field or a tightened constraint is caught before clients break.
Next: endpoints often need the same things before they can run: a database session, the logged-in user, settings, a rate-limit check. 3.14.4 shows FastAPI's answer, Depends, and how it builds and caches a graph of dependencies for every request.