If you run FastAPI or command-line services in production and are moving to Pydantic v2, these are the patterns that come up most. Pydantic v2 is close to a full rewrite on a Rust core, so the v1 habits for validators, settings and computed fields now produce code that fails or emits deprecation warnings. Environment settings moved to the separate pydantic-settings package, field validators got a new decorator that needs @classmethod, and discriminated unions (a tag field that tells Pydantic which variant to validate) became first-class. Each section below shows the v2 form of one pattern next to the v1 reflex it replaces, so you can finish a partial migration with confidence.
How to verify
Check which Pydantic and which patterns are in play:
pip show pydantic pydantic-settings | grep -E "^Name|^Version"
python -c "import pydantic; print(pydantic.VERSION)"
grep -rE "@validator|@root_validator|class Config:" app/ | head
grep -rE "@field_validator|@model_validator|model_config" app/ | head
grep -rE "from pydantic import BaseSettings" app/ | head # v1 import path
If you see both @validator (v1) and @field_validator (v2) in the same codebase, the migration is partial — finish it.
What’s happening
The v2 core (pydantic-core, written in Rust) parses and validates 5-50x faster than v1. The Python layer (pydantic) is now a thin wrapper that translates Python model definitions into core schemas. The API change reflects this: in v1, @validator modified a class attribute; in v2, @field_validator registers a function with the core schema. The semantics moved.
The settings story also changed. In v1, BaseSettings lived in pydantic and loaded from .env files and env vars. In v2, settings moved to a separate package pydantic-settings, which keeps Pydantic’s core slim and lets settings evolve independently. Code paths that import from pydantic import BaseSettings break at runtime.
Discriminated unions matter for any API that takes “an event of one of several shapes.” In v1, you’d validate by trial — try each variant in order, take the first that matched. In v2, you declare a discriminator field and the core dispatches by tag, which is both faster and produces better error messages.
Patterns
Settings (env config)
# requirements: pydantic-settings
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import Field, PostgresDsn
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env",
env_prefix="APP_",
case_sensitive=False,
extra="forbid",
)
database_url: PostgresDsn = Field(alias="DATABASE_URL")
secret_key: str = Field(min_length=32)
log_level: str = "INFO"
settings = Settings()
extra="forbid" is the production-safe choice — typo in an env var name fails at startup instead of silently being ignored.
Field validators (v2 style)
from pydantic import BaseModel, field_validator, ValidationError
class Order(BaseModel):
sku: str
quantity: int
@field_validator("sku")
@classmethod
def sku_upper(cls, v: str) -> str:
if not v.isalnum():
raise ValueError("sku must be alphanumeric")
return v.upper()
@field_validator("quantity")
@classmethod
def positive(cls, v: int) -> int:
if v <= 0:
raise ValueError("quantity must be positive")
return v
@classmethod is required in v2; v1 made it optional. Without it, mypy and Pydantic both complain.
Model validators (cross-field)
from pydantic import BaseModel, model_validator
from typing import Self
class DateRange(BaseModel):
start: int
end: int
@model_validator(mode="after")
def check_order(self) -> Self:
if self.start > self.end:
raise ValueError("start must be <= end")
return self
mode="after" runs after individual field validation. mode="before" operates on the raw input dict — use it for input shape transformations.
Discriminated unions
from typing import Literal, Annotated, Union
from pydantic import BaseModel, Field, TypeAdapter
class CardPayment(BaseModel):
method: Literal["card"]
last4: str
class BankTransfer(BaseModel):
method: Literal["bank"]
iban: str
Payment = Annotated[Union[CardPayment, BankTransfer], Field(discriminator="method")]
adapter = TypeAdapter(Payment)
p = adapter.validate_python({"method": "card", "last4": "4242"})
The core dispatches by method value, so an invalid method fails fast with one clean error instead of “tried CardPayment, failed; tried BankTransfer, failed; here are both stacks.”
Serialization
from pydantic import BaseModel
class User(BaseModel):
id: int
email: str
password_hash: str
# v2 dump
data = user.model_dump(exclude={"password_hash"})
json_str = user.model_dump_json(exclude={"password_hash"})
# v2 load
User.model_validate({"id": 1, "email": "x@y", "password_hash": "..."})
User.model_validate_json('{"id": 1, "email": "x@y", "password_hash": "..."}')
Method names changed from v1’s .dict(), .json(), .parse_obj(). The v1 names still work as deprecated aliases but emit a warning.
Computed fields (replacement for @property in models)
from pydantic import BaseModel, computed_field
class Rectangle(BaseModel):
width: float
height: float
@computed_field
@property
def area(self) -> float:
return self.width * self.height
computed_field includes the property in model_dump() output. A plain @property is hidden from serialization.
Common pitfalls
from pydantic import BaseSettings— broken in v2. Installpydantic-settingsand import from there.- Forgetting
@classmethodon validators — runs but mypy errors and Pydantic’s strict mode flags it. class Config:style configuration — v2 wantsmodel_config = ConfigDict(...). The oldclass Config:still works but is deprecated.- Setting
arbitrary_types_allowed = Trueon a public API model — disables type checking for foreign types, leading to runtime surprises. Use it only when the foreign type is yours and you control its shape. - Custom
__init__on a Pydantic model — v2 generates__init__from the schema and overriding breaks validation. Usemodel_validator(mode="before")to do pre-processing instead.
For FastAPI dependency injection that consumes Pydantic settings cleanly, see Deploying FastAPI under Uvicorn workers. Stack Harbor’s managed operations practice uses Pydantic v2 for every Python service config — the startup-time validation of env vars catches the bulk of “the new server doesn’t start” cases before deployment.