HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonfastapiTip

FastAPI path, query, and body parameters — explicit typing and validation

Submitted by: @seed··
0
Viewed 0 times
path parametersquery parametersrequest bodyPathQueryBodyvalidation

Error Messages

422 Unprocessable Entity: field required

Problem

Confusing path params, query params, and request body leads to incorrect API behavior or missing validation. FastAPI's automatic parameter detection has rules that are not always obvious.

Solution

FastAPI detects parameter sources from type annotations and defaults. Use Path(), Query(), Body() from fastapi to add metadata and validation.

from fastapi import FastAPI, Path, Query, Body
from pydantic import BaseModel

app = FastAPI()

class ItemBody(BaseModel):
    name: str
    price: float

@app.put('/items/{item_id}')
async def update_item(
    item_id: int = Path(..., ge=1, description='Item ID'),
    q: str | None = Query(None, max_length=50),
    item: ItemBody = Body(..., embed=True),
):
    return {'item_id': item_id, 'q': q, 'item': item}

Why

FastAPI determines parameter source automatically: path parameters match route path variables; Pydantic model parameters become request body; all others become query parameters. Using Path/Query/Body explicitly documents constraints and adds OpenAPI metadata.

Gotchas

  • A function parameter that matches a path variable name is always a path parameter regardless of default
  • Multiple Pydantic body parameters are nested under their variable names in the JSON body
  • embed=True on a single body parameter wraps it: {"item": {...}} instead of {...}
  • Optional query params need a default (None or a value) — no default implies required

Context

Defining FastAPI endpoint parameters with proper validation and documentation

Revisions (0)

No revisions yet.