skip to content

A FastAPI search endpoint silently ignores a client's misspelled ?limt=500 and serves the default page size; how do you make it reject unknown query parameters, and what traps come with it?

level: seniorimportance: should knowfreq 25%

answer

  1. plain parameters ignore extras
  2. a model behind Query()
  3. extra set to forbid
  4. it must be the only one
  5. headers are never alone

basics

~20 s

Group the parameters in a Pydantic model declared as Annotated[SearchParams, Query()] with extra='forbid'; unknown keys then get a 422 extra_forbidden. The model must hold every query parameter of the request, and the same setting on a header model rejects ordinary requests.

solid answer

~40 s

Individually declared query parameters ignore keys they do not know, so `?limt=500` simply leaves `limit` at its default. A **query parameter model**, `params: Annotated[SearchParams, Query()]`, with `model_config = {"extra": "forbid"}` validates the whole query string, and an unknown key gets a 422 with `type` `extra_forbidden` and `loc` `["query", "limt"]`. In FastAPI 0.143 the traps are: the model is only spread over the query string when it is the endpoint's **only** query parameter, so adding `q` beside it makes FastAPI expect a single `params` key and answer 422 `missing`; a forbid model in a dependency sees the endpoint's own query keys as extras; and a header model with `extra="forbid"` rejects every real request, because clients always send `Host`, `Accept` and `User-Agent`. Rolling it out also breaks clients that send cache-busting or tracking keys.

code

python · 21 lines
python
from typing import Annotated, Literal

from fastapi import FastAPI, Query
from pydantic import BaseModel, Field

app = FastAPI()


class SearchParams(BaseModel):
    model_config = {"extra": "forbid"}

    q: str | None = None
    limit: int = Field(20, ge=1, le=100)
    offset: int = Field(0, ge=0)
    order_by: Literal["created_at", "price"] = "created_at"
    tags: list[str] = []


@app.get("/items/")
async def search_items(params: Annotated[SearchParams, Query()]):
    return params

go deeper

for a junior

Recall that FastAPI ignores query keys it was not told about, and that a model declared with Query() can group parameters.

for a middle

Explain how Annotated[Model, Query()] maps fields to keys and how extra='forbid' turns an unknown key into a 422 extra_forbidden.

for a senior

Show you know the traps: the model must be the only query parameter, a dependency's model sees the endpoint's keys, header and cookie models cannot forbid extras, and clients sending junk keys break.

for a principal

Weigh strict query contracts against compatibility: strictness catches client bugs early, but it must arrive on new endpoints or versions with measured traffic, not as a silent flip.

## Why the typo goes unnoticed With individually declared parameters, FastAPI looks up each declared name in the query string and **ignores every other key**. A client that sends `?limt=500` gets `limit` at its default of 20, a 200, and no hint that its argument was dropped. For paging, filters or sort orders, that silent fallback can return the wrong data for months. ## Query parameter models with extra="forbid" Since FastAPI 0.115, a Pydantic model can declare a group of query parameters. You mark it with `Query()`: ```python class SearchParams(BaseModel): model_config = {"extra": "forbid"} q: str | None = None limit: int = Field(20, ge=1, le=100) offset: int = Field(0, ge=0) order_by: Literal["created_at", "price"] = "created_at" tags: list[str] = [] @app.get("/items/") async def search(params: Annotated[SearchParams, Query()]): ... ``` FastAPI collects the query string into the model and validates it as a whole: - each field is read from the key of the same name (repeated keys fill `list` fields); - the model's constraints apply, and the schema at `/docs` lists every field as a separate query parameter; - with `extra="forbid"`, an unknown key fails with `{"type": "extra_forbidden", "loc": ["query", "limt"], "msg": "Extra inputs are not permitted"}`. The same mechanism exists for headers with `Header()` and cookies with `Cookie()`. ## The traps, in the order teams hit them 1. **The model must be the only query parameter.** FastAPI 0.143 spreads a model over the query string only when it is the sole query parameter of that parameter list. Add `q: str | None = None` beside it and the model is treated as one ordinary parameter named `params`: every request gets 422 `missing` for `["query", "params"]`. Put every query field inside the model. 2. **A forbid model in a dependency sees everything.** If a dependency declares the model and the endpoint declares `q` itself, the model still receives the whole query string, and `q` fails as `extra_forbidden`. Again: one model, all the query fields. 3. **Header models cannot forbid extras in practice.** A header model receives every request header, and clients always send `Host`, `Accept`, `User-Agent` and more. With `extra="forbid"` each request fails with one `extra_forbidden` entry per ordinary header. 4. **Cookie models see the whole cookie jar.** Cookies set by other parts of the same site arrive too, so forbidding extras there rejects users for cookies your endpoint never asked for. 5. **Clients that send junk keys break.** Cache busters such as `_=1700000000` and tracking keys added by link builders become 422s the day you deploy. | Approach | Typo `?limt=` | Extra junk keys | Fits headers | |---|---|---|---| | Separate `Query()` params | ignored silently | ignored | not applicable | | Model, default extras | ignored silently | ignored | yes | | Model, `extra="forbid"` | 422 | 422 | no | ## When you cannot forbid yet Strict rejection is not the only tool. While clients are being cleaned up you can make unknown keys visible without breaking anyone: - Keep the model permissive and add a small dependency that receives the `Request`, compares `request.query_params.keys()` with the model's field names, and logs the unknown ones. - Watch those logs per endpoint and per client; a misspelled key such as `limt` stands out quickly. - Switch the model to `extra="forbid"` once the logs are quiet, or once every caller has moved to a version that sends only documented keys. ## Rolling it out safely - Introduce the forbid model on new endpoints first, or behind a new API version, rather than flipping an existing public endpoint. - Before switching, log the query keys an endpoint actually receives, so you know which clients send extras. - Document the accepted keys; the generated schema already lists the model's fields. - Keep header and cookie models permissive and validate only the fields you declare.

  • In FastAPI 0.143, how can you tell from the generated schema that a query model is not being spread over the query string?
    When the model is the sole query parameter, the schema lists each field as its own query parameter. When something else sits beside it, the schema shows a single required parameter named after the function argument whose schema references the model. That listing, and a 422 `missing` for that name, are the signs the model is being treated as one value.
  • In FastAPI, why is forbidding extra query keys a breaking change even when every documented parameter stays the same?
    Clients often send keys the server never read: cache busters, tracking parameters, or leftovers from an older version. They were harmless while ignored; with `extra="forbid"` they become 422s. Measure what callers send before switching, and introduce it on new endpoints or a new version.

  • FastAPI rejects unknown query parameters by default.
  • A query model can be combined freely with other separate query parameters.
  • extra='forbid' on a header model only rejects headers the client invents.
  • Forbidding extra query keys never affects existing clients.
  • A query model's fields are hidden from the generated docs.

Assumes FastAPI 0.143; query, header and cookie parameter models exist since 0.115, and the rule that a model is spread only when it is the function's sole query, header or cookie parameter is 0.143's behaviour.