Introduction
Pydantic models help you define clear and simple data shapes. They check data automatically so your app gets the right info.
Pydantic models help you define clear and simple data shapes. They check data automatically so your app gets the right info.
from pydantic import BaseModel class ModelName(BaseModel): field_name: field_type another_field: another_type = default_value
Models inherit from BaseModel.
Fields are defined with type hints and optional default values.
from pydantic import BaseModel class User(BaseModel): name: str age: int
from pydantic import BaseModel class Product(BaseModel): id: int price: float = 0.0
from pydantic import BaseModel from typing import Optional class Item(BaseModel): description: Optional[str] = None
This example shows how to define a Pydantic model and create an instance. It prints the whole object and each field.
from pydantic import BaseModel class Person(BaseModel): name: str age: int # Create a person instance person = Person(name="Alice", age=30) print(person) print(person.name) print(person.age)
Pydantic automatically checks that data types match.
If data is wrong, it raises clear errors to help fix it.
Models can be nested to build complex data shapes.
Pydantic models define data shapes with types.
They validate data automatically.
Use them to keep your app data clean and safe.
Pydantic model in FastAPI?name and an optional integer field age?name: str (required) and age: Optional[int] = None (optional), which is correct.from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
price: float
item = Item(id='5', name='Book', price=12.99)item.id after creation?item.id becomes int 5.from pydantic import BaseModel
class Product(BaseModel):
name: str
price: float = 'free'price expects a float but is given a string default 'free'.User with a required username (string), an optional email (string), and a roles list of strings that defaults to an empty list. Which is the correct way to define it?Optional[str] = None to allow missing value.roles: list[str] = [] is unsafe because lists are mutable defaults shared across instances. Use Field(default_factory=list) to create a new list each time.Pass the test and this pattern moves unknown