Pydantic request bodies — automatic validation
Define a Pydantic model with typed fields. FastAPI validates the JSON body, returns 422 if invalid.
main.py
v3.1
API simulator
click Simulate
Click "Simulate" to see what this FastAPI app does.
🧠 How it works
Pydantic BaseModel defines the SHAPE of the JSON body. Field(...) — required. Field(default) — optional with default. Constraints: min_length, max_length, ge (>=), le (<=), gt (>), lt (<), regex. Special types: EmailStr, HttpUrl, IPvAnyAddress, conint(ge=0, le=100). Optional[T] = None — explicitly optional, defaults to None. Type hints VALIDATE: wrong type → 422 with detailed error pointing at the field. response_model on the route validates the OUTPUT too — strips extra fields, validates types. user.model_dump() converts Pydantic model → dict (v2). In v1 it was .dict(). Benefits: no manual validation, free /docs, type-safe serialization.
✏️ Try these changes
-
Change min_length=3 to min_length=5→ usernames shorter than 5 chars now 422 -
Add a new field password: str = Field(..., min_length=8)→ password now required -
Change is_active: bool = True to is_active: bool = False→ default flips -
Remove the response_model from /users2→ extra_field is now included in the response