Request Models with Pydantic
A Pydantic model replaces checks written by hand with a class that names each field of a request body and its type, with defaults for fields that may be left out, None for optional ones, and models inside models, and FastAPI checks every request against it before the route runs.
Apprentice · FastAPI · Python · Updated
After this lesson you can
- Describe a request body with a Pydantic model, with required fields, defaults and optional fields that may be None
- Nest a model inside a model and use a list of models, and use the model as a route's body
Key takeaways
- A model based on BaseModel names each field of a body and its type, and Pydantic checks every field and reports every problem at once.
- A field with a default value may be left out of the body, and the model fills in the default.
- A field typed str | None with a default of None is optional, so it's None when it isn't sent.
- A field whose type is another model, or a list of models, describes JSON with objects and lists inside it.
- Pydantic turns a value into its field's type when it safely can, such as the text "34" into 34, and refuses what it can't.
Most request bodies an API takes are bigger than a game's four fields: a sign-up, a booking or a job application has a dozen fields, some required, some optional, some holding lists. Checking each one by hand, as Checking Input by Hand did, means a long function for every route. This lesson describes Happy Tails' whole adoption application as one Pydantic model, and FastAPI checks every request against it for you.
One class instead of a dozen checks
Taking JSON In: Your First Request Body used a small model for a new game. A model is a class based on BaseModel, and each line inside it is a field: its name, a colon, and its type. age: int is read "age is an int". Here is the whole application:
from pydantic import BaseModel
class Application(BaseModel):
name: str
email: str
age: int
pet_name: str
pet_type: str
has_yard: bool = False
phone: str | None = None
application = Application(name="Maya", email="maya@example.com", age="34", pet_name="Biscuit", pet_type="dog")
print(application.age + 1)
print(application.has_yard)
print(application.phone)
35
False
None
The age was sent as the text "34", and Pydantic turned it into the number 34, so age + 1 works. It does that when the change is safe: "34" becomes 34, and "yes" becomes True for a bool. Text such as "fifteen" can't become a whole number, so it's refused. Pydantic checks every field and reports every problem at once, the work Checking Input by Hand did with a list.
Defaults and optional fields
Five fields have no =, so they're required: a body without one is refused. The last two may be left out:
- A default:
has_yard: bool = False. When the body doesn't sendhas_yard, it'sFalse. - An optional field:
phone: str | None = None, read "phone is a str or None, and None unless it's sent". The|(read "or") lets the field hold either type, andNonemeans "nothing given", which isn't the same as the empty text"". Older code writes the same thing asOptional[str].
Without the = None, str | None is still required: the body must send phone, though it may send null. It's the default that makes a field optional.
Models inside models
Happy Tails also asks about the home and the pets already living there. In JSON, that's an object inside the application, and a list of objects:
{"name": "Rosa", "age": 61, "pet_type": "rabbit", "home": {"has_yard": true, "renting": false}, "current_pets": [{"name": "Pickles", "pet_type": "cat"}]}
Each inner object gets a model of its own, and the outer model uses it as a field's type. Here's a shorter application, to keep the example small:
from pydantic import BaseModel
class CurrentPet(BaseModel):
name: str
pet_type: str
class Home(BaseModel):
has_yard: bool
renting: bool
class Application(BaseModel):
name: str
age: int
pet_type: str
home: Home
current_pets: list[CurrentPet] = []
application = Application(name="Rosa", age=61, pet_type="rabbit", home={"has_yard": True, "renting": False},
current_pets=[{"name": "Pickles", "pet_type": "cat"}])
print(application.home.has_yard)
print(application.current_pets[0].name)
print(application.model_dump())
True
Pickles
{'name': 'Rosa', 'age': 61, 'pet_type': 'rabbit', 'home': {'has_yard': True, 'renting': False}, 'current_pets': [{'name': 'Pickles', 'pet_type': 'cat'}]}
home: Home is a nested model: Pydantic checks the inner object against Home, and a second dot reads into it, application.home.has_yard. list[CurrentPet] is read "a list of CurrentPet": every item in the list is checked as a CurrentPet. The = [] makes the list optional, empty when it isn't sent. And model_dump() turns the inner models into dictionaries too.
The model as the route's body
In a route, the model goes where Taking JSON In: Your First Request Body put NewGame, and FastAPI reads the body, checks it and hands the route a ready Application. With the whole application from the first section:
@app.post("/applications", status_code=201)
def apply(application: Application):
saved = {"id": len(APPLICATIONS) + 1, **application.model_dump()}
APPLICATIONS.append(saved)
return saved
Rosa applies for Clover the rabbit, with no phone. Two applications are on file, so she gets id 3, and the answer is 201 Created with the defaults filled in:
{"id":3,"name":"Rosa","email":"rosa@example.com","age":61,"pet_name":"Clover","pet_type":"rabbit","has_yard":true,"phone":null}
Now send the bad body from Checking Input by Hand, with a pet name added and no email: {"name": "", "age": 15, "pet_name": "Clover", "pet_type": "dragon"}. The answer is 422, before the route runs, and it names one problem:
{"detail":[{"type":"missing","loc":["body","email"],"msg":"Field required","input":{"name":"","age":15,"pet_name":"Clover","pet_type":"dragon"}}]}
Only one, because every other value has the right type: an empty name is still text, 15 is still a whole number, and "dragon" is still text. A type isn't a rule. Field Rules: Lengths, Ranges and Choices adds the rules.
Check yourself
2 questions to try on the lesson page.
So what
A model is the request body's description written once, in one place: FastAPI checks every request against it, fills in the defaults, and hands your route data it can trust to have the right shape.