Pydantic: Required vs. Optional Fields

In Pydantic, a field is required by default. To make it optional, you must provide a default value, like `name: str = "guest"` or `age: int | None = None`. This is key for flexible API request bodies.
A Pydantic field is required unless given a default value. Make a field optional by assigning a default (`name: str = "guest"`) or by allowing None (`age: int | None = None`). This is crucial for defining flexible API request bodies in frameworks like FastAPI where clients might omit certain fields. The common mistake is using `my_field: str = Field(...)`; this adds metadata but does not set a default. To do both, use `my_field: str = Field(default="value")`.
Read the original → pydantic.dev
- #python
- #pydantic
- #fastapi
- #data validation
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.