Pydantic for Data Validation and Type Conversion

Use Python type hints to validate input, convert values, and describe nested data with Pydantic.

On this page

Pydantic for Data Validation and Type Conversion

Unexpected input and type errors can turn a small Python script into a lot of defensive code. Pydantic uses type hints to validate and convert data for you.

Install Pydantic

pip install pydantic
Bash

NOTE

See the Pydantic installation guide for more setup options.

Basic usage

The usual starting point is a model. Suppose we have a class called User.

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    signup_ts: str | None = None
    friends: list[int] = []

user = User(id=123, name='John Doe', signup_ts="2024-05-01T12:00", friends=[1, 2, 3])

print(user)
print(user.id)
print(user.dict())  # 轉成 dictionary
Python

Automatic type conversion

Pydantic can convert values to the declared type when it knows how. Here's an example.

user = User(id='123', name='John Doe', signup_ts=None, friends=[1, '2', b'3'])
print(user)
Python
# id=123 name='John Doe' signup_ts=None friends=[1, 2, 3]
Python

Pydantic attempts the conversion and raises a ValidationError if it fails.

  • '123' becomes 123.
  • [1, '2', b'3'] becomes [1, 2, 3].

Validation errors

What happens when a value cannot be converted?

from pydantic import BaseModel, ValidationError


class User(BaseModel):
    id: int
    name: str
    signup_ts: str | None = None
    friends: list[int] = []

try:
    User(id='not-an-int', name='John Doe')
except ValidationError as e:
    print(e)
Python
# 1 validation error for User
# id
#   Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='not-an-int', input_type=str]
#     For further information visit https://errors.pydantic.dev/2.11/v/int_parsing
Python

Nested models

For more complex data, you can use one model as the field type of another.

class Address(BaseModel):
    street: str
    city: str

class User(BaseModel):
    name: str
    address: Address

u = User(name="Alice", address={"street": "1st Street", "city": "Metropolis"})
print(u.address.street)
Python
# 1st Street
Python

Dumping and copying models

from pydantic import BaseModel, ValidationError


class User(BaseModel):
    id: int
    name: str

user = User(id=123, name='John Doe')

print(user.model_dump())  # Dictionary
print(user.model_dump_json())  # JSON string
new_user = user.model_copy(update={'name': 'Jane Doe'})
print(new_user)
Python
# {'id': 123, 'name': 'John Doe'}
# {"id":123,"name":"John Doe"}
# id=123 name='Jane Doe'
Python

NOTE

The older dict(), json(), and copy() methods are deprecated. Pydantic v2 uses model_dump(), model_dump_json(), and model_copy().

Field configuration

What you want to doHow to do it
Require a fieldField(...)
Set a defaultField(default_value)
Restrict a numeric rangegt=, ge=, lt=, le=
Limit string or list lengthmin_length=, max_length=
Describe the field in API docstitle=, description=
Accept input under a different namealias="other_name"
Exclude a field from outputexclude=True
Compute a default for each instancedefault_factory=...
from pydantic import BaseModel, Field

class User(BaseModel):
    id: int = Field(..., gt=0, lt=9999) # 必填且介於0-9999之間
    name: str = Field(..., Harry) # 必填且default value是Harry
Python

Closing note

These model definitions also work well with FastAPI, where they can describe request data and drive validation.