Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

DJ
Django & FastAPI
0/12 completed
Beginner
How Python web frameworks workYour first FastAPI appRequest bodies and Pydantic models
Intermediate
FastAPI with a databaseDependencies, routers and testingDjango: projects, apps and the ORMDjango views, URLs and templatesForms, the admin and class-based views
Advanced
APIs with Django REST frameworkAuthentication in Django and FastAPIBackground tasks and async
Pro
Deploying Python web apps
Tracks / Django & FastAPI / Beginner

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

Python · editable

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:

Python · editable
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:

Python · editable

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

Python · editable

model_dump(exclude_unset=True) returns only the fields the client actually sent, which is exactly what a PATCH needs.

Practice

  1. Add a Review model (stars 1–5, text up to 500 characters) and a POST /products/{product_id}/reviews route.
  2. Give OrderCreate a @model_validator that rejects orders with more than 20 items in total.
  3. Add a ProductPublic response model that adds a computed price_with_tax field.
✎ Check your understanding

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?

← Your first FastAPI app