Request bodies and Pydantic models
To create or update data, clients send a JSON body. In FastAPI you describe its shape with a Pydantic model: a class with typed fields. FastAPI then parses the JSON, validates every field, converts types, and hands your function a ready-to-use Python object.
A model for the request body
Because the parameter's type is a Pydantic model, FastAPI reads it from the body. Note the conversions: the string "8.99" became the float 8.99, and defaults were filled in. Invalid data got a 422 listing every problem, with its exact location.
Pydantic on its own
Pydantic is a standalone library; you can use models anywhere in your code:
| Feature | Example |
|---|---|
| Constraints | Field(min_length=2), Field(ge=0, le=100), Field(pattern=r"…") |
| Defaults | quantity: int = 1, tags: list[str] = [] (safe in Pydantic) |
| Nested models | address: Address, items: list[OrderItem] |
| Special types | datetime, date, UUID, Decimal, Literal["a", "b"], EmailStr (needs email-validator) |
| Custom checks | @field_validator, @model_validator |
| Export | .model_dump(), .model_dump_json() |
Separate models for input and output
The data a client sends isn't the same as what the API returns. A user signs up with a password, but the password must never come back. Use separate models and tell FastAPI the output shape with response_model:
The stored user had password and password_hash, but the response contained only id, username and email: response_model is a safety net against leaking fields.
Nested models and updates
model_dump(exclude_unset=True) returns only the fields the client actually sent, which is exactly what a PATCH needs.
Practice
- Add a
Reviewmodel (stars1–5,textup to 500 characters) and aPOST /products/{product_id}/reviewsroute. - Give
OrderCreatea@model_validatorthat rejects orders with more than 20 items in total. - Add a
ProductPublicresponse model that adds a computedprice_with_taxfield.
1.How does FastAPI know a parameter comes from the request body?
2.What does response_model=UserPublic do?
3.Why use model_dump(exclude_unset=True) in a PATCH handler?