skip to content

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%

answer

  1. name, annotation, marker
  2. the path template wins first
  3. scalar versus model
  4. explicit markers override inference

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().

solid answer

~40 s

FastAPI inspects the signature once, when the route is registered. A parameter whose name appears in the path template, such as `item_id` in `/items/{item_id}`, is a path parameter. Otherwise, with no explicit marker, a scalar annotation (`int`, `str`, `float`, `bool`, an `Enum`) becomes a **query** parameter and a non-scalar one (a Pydantic model, a `list` or `dict`) becomes the **body**. Explicit markers such as `Query()`, `Path()`, `Header()`, `Cookie()` and `Body()`, ideally inside `Annotated`, override the inference, and special types like `Request` or `BackgroundTasks` are injected rather than bound. The raw string is then converted to the annotated type, and a failure answers 422 with a `loc` such as `["path", "item_id"]`.

code

python · 25 lines
python
from typing import Annotated

from fastapi import FastAPI, Header
from pydantic import BaseModel

app = FastAPI()


class PriceAlert(BaseModel):
    max_price: float


@app.post("/items/{item_id}/alerts")
async def create_alert(
    item_id: int,
    alert: PriceAlert,
    notify: bool = False,
    x_client_id: Annotated[str | None, Header()] = None,
):
    return {
        "item_id": item_id,
        "max_price": alert.max_price,
        "notify": notify,
        "client": x_client_id,
    }

go deeper

for a junior

Recall the rule of thumb: in the path template means path, a scalar means query, a model means body, and headers or cookies need an explicit marker.

for a middle

Explain that inference happens once at registration, that list types default to the body, and how the loc in a 422 reveals which source FastAPI picked.

for a senior

Show you debug binding by reading the generated schema and the 422 loc, and that you insist on explicit Annotated markers so a renamed path placeholder cannot silently turn a path parameter into a query parameter.

for a principal

Frame explicit markers versus inference as a team convention: inference is concise, but explicit Annotated markers make reviews and refactors safer in a large codebase.

## The question FastAPI answers for every parameter A **path operation function** is the Python function under a decorator such as `@app.get(...)` or `@app.post(...)`. FastAPI never looks at the HTTP request to decide where a parameter comes from. It decides once, when the route is registered, by inspecting the function signature: each parameter's **name**, its **type annotation**, and any **marker** found in `Annotated[...]` or in the default value. ## The inference rules, in the order FastAPI applies them 1. **Explicit marker first.** If the parameter carries `Query()`, `Path()`, `Header()`, `Cookie()`, `Body()`, `Form()`, `File()` or `Depends()`, that marker decides the source. The recommended spelling is `Annotated[int, Query(ge=1)]`. 2. **Special framework types.** An annotation of `Request`, `WebSocket`, `Response`, `BackgroundTasks` or `SecurityScopes` is injected by FastAPI and is not read from the request data at all. 3. **Name in the path template.** If the name matches a `{placeholder}` in the route path, it is a **path parameter**. Putting `Query()` on such a name fails at startup with the assertion "Cannot use `Query` for path param". 4. **Non-scalar annotation.** A Pydantic model, a `list`, a `dict` or another structured type without a marker becomes part of the **request body** (how bodies are shaped is covered with JSON body binding). 5. **Everything else is a query parameter.** A scalar such as `int`, `float`, `str`, `bool`, `UUID`, `datetime` or an `Enum` with no marker is read from the query string. | Declaration | Source FastAPI picks | |---|---| | `item_id: int` with `/items/{item_id}` | path | | `limit: int = 10` | query | | `alert: PriceAlert` (a `BaseModel`) | body | | `tags: list[str]` with no marker | body | | `tags: Annotated[list[str], Query()] = []` | query, repeated `?tags=` keys | | `x_client_id: Annotated[str \| None, Header()] = None` | the `X-Client-Id` header | The order of parameters in the signature does not matter; FastAPI matches by name, type and marker, not position. ## Two consequences people trip over - **Headers and cookies are never inferred.** A parameter called `user_agent: str | None = None` is a *query* parameter named `user_agent` unless it is declared with `Header()`. The same holds for cookies and `Cookie()`. - **A list is a body unless you say otherwise.** `tags: list[str]` on a GET endpoint ends up as a JSON request body in the schema. To read `?tags=a&tags=b` you must write `Annotated[list[str], Query()]`. ## Conversion and validation follow the source Path segments, query values, headers and cookies all arrive as **strings**. Once FastAPI knows the source, it hands the string to Pydantic with the annotated type, so `item_id: int` receives the integer `3`, not `"3"`. When conversion fails, FastAPI does not call the function; it answers with a **422** and a `detail` list in which each `loc` names the source and the parameter: - `{"type": "int_parsing", "loc": ["path", "item_id"], ...}` for `/items/abc` - `{"type": "missing", "loc": ["query", "needy"], ...}` for a required query parameter left out The first element of `loc` is how you read back which source FastAPI chose, which is the fastest way to debug a parameter that is "never filled". ## Debugging a parameter that is never filled When a value the client clearly sends never arrives, work through the same steps every time: 1. **Read the 422, if there is one.** Its `loc` says where FastAPI looked: `["query", "user_agent"]` means it expected a query parameter, not a header. 2. **Read the generated schema.** In `/docs`, or in `app.openapi()`, each parameter carries `in: path`, `in: query`, `in: header` or `in: cookie`, and body parameters appear under `requestBody`. FastAPI builds that schema from the same analysis it uses for binding. 3. **Compare names exactly.** A path placeholder `{item_id}` and a parameter `itemId` are different names, so the parameter silently becomes a query parameter and the path value is never bound to it. 4. **Make the source explicit.** Adding the marker you meant, such as `Header()`, turns an inference surprise into a declaration a reviewer can read. The same rules apply to the parameters of a dependency function, so a dependency that declares `token: str` is reading a query parameter called `token` unless it says otherwise (dependency wiring itself is covered with sub-dependency reuse). ## Why this design matters in practice - **The schema at `/docs` reflects the same decisions**, so the interactive docs show a parameter as path, query, header or body exactly as FastAPI will bind it. - **Mistakes surface early**: a marker that contradicts the path template fails at import time instead of at the first request. - **The function stays callable as plain Python** when markers live in `Annotated`, because the default after `=` is a real default.

  • In FastAPI, can a parameter's source change if you reorder the function's parameters?
    No. FastAPI binds by name, annotation and marker, not by position, so reordering changes nothing. Order only matters to Python itself: without `Annotated`, a parameter with a default cannot precede one without, which is why older code used a leading `*`. With `Annotated` markers the default sits after `=` and the problem disappears.
  • In FastAPI, how do you see which source was chosen for each parameter without sending requests?
    Open `/docs` or read `app.openapi()`: each parameter is listed with `in: path`, `in: query`, `in: header` or `in: cookie`, and body parameters appear under `requestBody`. FastAPI builds that schema from the same analysis it uses to bind requests, so it is a faithful map of the inference.

  • FastAPI binds parameters by their position in the function signature.
  • Any parameter missing from the path template is read from the JSON body.
  • A parameter named user_agent is filled from the User-Agent header automatically.
  • A path value that fails int conversion makes FastAPI answer 404.
  • Type annotations are only for the editor; the function receives raw strings.