Phase 18 of 25 · Topic 18.2

FastAPI Path, Query & Body Validation with Pydantic

1Concept

FastAPI validates incoming HTTP parameters against Python type annotations. Path parameters (`/users/{user_id}`), Query parameters (`?limit=10`), and JSON Body payloads (`UserCreate`) are validated and serialized automatically.

2Architecture Diagram

POST /items?notify=true
Body: {"name": "Widget", "price": 29.99} ---> Validated by Pydantic Model automatically!

3Code Example

Python 3.12
validation_example = '''
from fastapi import FastAPI, Query, Path
from pydantic import BaseModel, Field

class OrderCreate(BaseModel):
    item_id: int
    quantity: int = Field(gt=0, le=100)
    price: float

app = FastAPI()

@app.post("/orders/{order_id}")
async def create_order(
    order_id: int = Path(..., ge=1000),
    order: OrderCreate = ...,
    priority: bool = Query(default=False)
):
    return {"order_id": order_id, "status": "CREATED", "priority": priority}
'''
print("=== Request Parameter Validation Pipeline ===")
print(validation_example.strip())

4Expected Output

=== Request Parameter Validation Pipeline ===
from fastapi import FastAPI, Query, Path
from pydantic import BaseModel, Field

class OrderCreate(BaseModel):
    item_id: int
    quantity: int = Field(gt=0, le=100)
    price: float

app = FastAPI()

@app.post("/orders/{order_id}")
async def create_order(
    order_id: int = Path(..., ge=1000),
    order: OrderCreate = ...,
    priority: bool = Query(default=False)
):
    return {"order_id": order_id, "status": "CREATED", "priority": priority}

5Key Takeaways

  • Returns HTTP 422 Unprocessable Entity with exact field-level errors on validation failure.
  • `Path(...)` marks path parameters; `Query(...)` configures query strings.
  • Pydantic models define request payloads and response models (`response_model=OrderResponse`).