← Back to FastAPI, page 2

fastapi-0034 · Medium mid

How do you handle many filter parameters and nested or list request bodies in FastAPI?

Group related query parameters into a Pydantic model and declare it as Annotated[Filters, Query()] (FastAPI 0.115+), which validates them together and documents each one; model_config = {"extra": "forbid"} rejects unknown filters. For bodies, Pydantic models can nest other models and lists, such as an exam with a list of question objects, and an endpoint can accept a list of models directly. Limit list sizes to protect the server.

Full answer

Grouped query parameters

An endpoint with eight filters becomes hard to read and repeat. Since FastAPI 0.115:

python
class MarkFilters(BaseModel):
    model_config = {"extra": "forbid"}
    subject: str | None = None
    min_score: int = Field(0, ge=0, le=100)
    term: Literal["mid", "final"] = "final"
    tags: list[str] = []

@app.get("/marks")
def list_marks(filters: Annotated[MarkFilters, Query()]): ...
  • Each field is still a separate query parameter (?subject=Maths&min_score=40), validated and documented.
  • extra="forbid" returns 422 for unknown parameters, which catches typos like min_scroe.
  • The same pattern works for headers (Header()), cookies (Cookie()) and forms (Form()).
  • Before 0.115, the usual approach was a dependency class or function.

Nested bodies

Pydantic models can contain other models, lists and dicts:

python
class Question(BaseModel):
    text: str
    options: list[str] = Field(min_length=2, max_length=6)
    answer_index: int

class Exam(BaseModel):
    title: str
    questions: list[Question] = Field(min_length=1, max_length=100)

Validation errors point to the exact location, such as ["body", "questions", 2, "options"].

List bodies: def bulk(students: list[StudentIn]) accepts a JSON array at the top level. Add a length limit (with Annotated[list[StudentIn], Field(max_length=500)] or by checking) so one request cannot submit a million items.

Other body shapes: dict[str, int] for maps (keys arrive as strings and are converted), and discriminated unions for "one of several shapes".

Keep request payloads bounded: limit list lengths and string sizes, and set a request size limit at the proxy.

python
from typing import Annotated, Literal

from fastapi import FastAPI, Query
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field

app = FastAPI()


class MarkFilters(BaseModel):
    model_config = {"extra": "forbid"}
    subject: str | None = None
    min_score: int = Field(0, ge=0, le=100)
    term: Literal["mid", "final"] = "final"
    tags: list[str] = []


class Question(BaseModel):
    text: str
    options: list[str] = Field(min_length=2, max_length=6)
    answer_index: int = Field(ge=0)


class Exam(BaseModel):
    title: str
    questions: list[Question] = Field(min_length=1, max_length=100)


class StudentIn(BaseModel):
    roll_no: str
    name: str


@app.get("/marks")
def list_marks(filters: Annotated[MarkFilters, Query()]):
    return filters


@app.post("/exams")
def create_exam(exam: Exam):
    return {"title": exam.title, "questions": len(exam.questions)}


@app.post("/students/bulk")
def bulk(students: Annotated[list[StudentIn], Field(max_length=3)]):
    return {"created": [s.roll_no for s in students]}


c = TestClient(app)
print(c.get("/marks?subject=Maths&min_score=40&tags=unit1&tags=unit2").json())
print(c.get("/marks?min_scroe=40").json()["detail"][0]["type"])

exam = {"title": "Unit test 1", "questions": [
    {"text": "2 + 2 = ?", "options": ["3", "4"], "answer_index": 1},
    {"text": "Capital of India?", "options": ["Delhi"], "answer_index": 0}]}
print(c.post("/exams", json=exam).json()["detail"][0]["loc"])
exam["questions"][1]["options"].append("Mumbai")
print(c.post("/exams", json=exam).json())

students = [{"roll_no": f"R{i}", "name": "x"} for i in range(4)]
print(c.post("/students/bulk", json=students[:2]).json(), c.post("/students/bulk", json=students).status_code)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'subject': 'Maths', 'min_score': 40, 'term': 'final', 'tags': ['unit1', 'unit2']} extra_forbidden ['body', 'questions', 1, 'options'] {'title': 'Unit test 1', 'questions': 2} {'created': ['R0', 'R1']} 422

Key points

  • Annotated[Model, Query()] groups query parameters (0.115+)
  • extra='forbid' rejects unknown filters
  • Models nest other models and lists
  • Errors include precise locations like questions.2.options
  • Bound list lengths in bodies

Common mistakes

  • Repeating the same eight query parameters across endpoints
  • Accepting unbounded lists in request bodies
  • Silently ignoring misspelled filter names
  • Flattening naturally nested data into awkward field names

Follow-ups

  • How did people group query parameters before FastAPI 0.115?
  • How would you validate that answer_index is within the options list?
  • How would you accept a body that can be one of three shapes?

Tips

  • Mention the 0.115 Query model feature by version
  • Show the precise error locations for nested data
  • Always bound list sizes