Pydantic in Python: Models, Validators, Settings, and the 2.14 Changes
Learn Pydantic in Python with tested code: BaseModel, Field, validators, strict mode, TypeAdapter, settings from env vars, and what changed in 2.14.

Learn Pydantic in Python with tested code: BaseModel, Field, validators, strict mode, TypeAdapter, settings from env vars, and what changed in 2.14.

Pydantic is a Python library that validates data against type hints. Its documentation calls it "the most widely used data validation library for Python," and its core lives in pydantic-core, a separate package where validation for most types is implemented in Rust. You declare a class, pass it messy input, and get back typed objects or a precise error.
The current release is pydantic 2.14.4, published on 19 November 2026, and the package logged 1,238,139,685 downloads in the last month as of 5 December 2026. Every code block in this guide ran on Python 3.15.2 with pydantic 2.14.4 and pydantic-settings 2.16.4.
It goes from your first BaseModel to fields, validators, serialization, strict mode, settings from environment variables, measured performance, and the release changes that make older tutorials wrong.
"42" becomes the integer 42. Turn on strict mode when a wrong type should fail instead.model_validate_json() or TypeAdapter.validate_json(). In our test on 10,000 objects it ran about 1.6x faster than json.loads() followed by validation.pydantic-settings. Init arguments beat environment variables, which beat a .env file, which beats the defaults..dict() or parse_obj() is teaching the old API.Pydantic turns type hints into runtime checks. You subclass BaseModel, annotate each field, and Pydantic builds a validator from those annotations. When data arrives from a request, a file, or an API, the model either returns a typed instance or raises ValidationError with every problem listed.
The library is free and MIT licensed, with 29,851 GitHub stars as of 5 December 2026. The company behind it also builds Pydantic AI, an agent framework that accepts a Pydantic model as an agent's output type, and Logfire, an observability platform. This guide covers the validation library only.

Pydantic gives you four ways to define a schema: BaseModel, Pydantic dataclasses, TypeAdapter for any type, and the validate_call decorator for function arguments. Most code uses BaseModel, so most of this guide does too.
The FastAPI home page says it "stands on the shoulders of giants: Starlette for the web parts. Pydantic for the data parts," and Typer's maintainer announced on 9 November 2026 that in Typer 0.29.0 "the validation is done with @pydantic." The docs count 8,119 PyPI packages that depend on it "at the time of writing."
Pydantic 2.14 shipped on 8 October 2026, dropped Python 3.9 and added Python 3.15. Three weeks later the 1.10.27 release notes said: "This is the last V1 Pydantic release. V1 support (including the pydantic.v1 namespace in Pydantic V2) fully ends after this release."
Start with three steps: install it, define a model, and read the errors it raises.
python -m venv .venv
source .venv/bin/activate
pip install -q pydantic==2.14.4 pydantic-settings==2.16.4
python -c "import pydantic, pydantic_settings; print(pydantic.VERSION, pydantic_settings.__version__)"2.14.4 2.16.4PyPI lists pydantic 2.14.4 as requiring Python 3.10 or newer, and pydantic-settings 2.16.4 as requiring Python 3.11 or newer. The settings package also installs python-dotenv, so .env files work without another install. Our uv guide shows uv add pydantic as a faster alternative to venv and pip.
A model is a class with annotated fields. This one takes strings for every field and shows what Pydantic does with them.
from datetime import date
from pydantic import BaseModel, ValidationError
class Order(BaseModel):
id: int
customer: str
total: float
shipped_on: date | None = None
order = Order(id="42", customer="Ada", total="19.90", shipped_on="2026-12-05")
print(order)
print(order.model_dump())
try:
Order(id="forty-two", customer="Ada", total=19.9)
except ValidationError as exc:
print(exc.error_count(), exc.errors()[0]["type"], exc.errors()[0]["loc"])id=42 customer='Ada' total=19.9 shipped_on=datetime.date(2026, 12, 5)
{'id': 42, 'customer': 'Ada', 'total': 19.9, 'shipped_on': datetime.date(2026, 12, 5)}
1 int_parsing ('id',)"42" became 42 and the ISO string became a date. This is lax mode, the default. The docs describe it as Pydantic trying "to coerce data to the correct type where appropriate." "forty-two" cannot become an integer, so validation fails with the error type int_parsing at location id.
A ValidationError collects every failure in one pass, including failures inside nested models and lists. That makes it useful as an API response body: the client sees all problems at once.
from typing import Annotated, Literal
from pydantic import BaseModel, Field, ValidationError
class LineItem(BaseModel):
sku: Annotated[str, Field(min_length=3, pattern=r"^[A-Z0-9-]+$")]
quantity: int = Field(gt=0, le=100)
unit_price: float = Field(ge=0)
class Order(BaseModel):
id: int
status: Literal["pending", "paid", "shipped"] = "pending"
items: list[LineItem]
try:
Order(id=1, status="lost", items=[{"sku": "ab", "quantity": 0, "unit_price": 5}])
except ValidationError as exc:
print(exc)3 validation errors for Order
status
Input should be 'pending', 'paid' or 'shipped' [type=literal_error, input_value='lost', input_type=str]
For further information visit https://errors.pydantic.dev/2.14/v/literal_error
items.0.sku
String should have at least 3 characters [type=string_too_short, input_value='ab', input_type=str]
For further information visit https://errors.pydantic.dev/2.14/v/string_too_short
items.0.quantity
Input should be greater than 0 [type=greater_than, input_value=0, input_type=int]
For further information visit https://errors.pydantic.dev/2.14/v/greater_thanEach entry names the path (items.0.sku), the rule, the input, and a link to the error page for that error type. Call exc.errors() when you need the same data as a list of dicts for JSON.
Annotations set the type. Field() adds constraints, defaults, aliases, and documentation on top.
The LineItem model above shows both styles. quantity: int = Field(gt=0, le=100) puts the constraint in the default slot. Annotated[str, Field(min_length=3)] puts it in the type, which lets you reuse the type across models:
Constraint | Applies to | Example |
|---|---|---|
| numbers |
|
| numbers |
|
| strings, lists |
|
| strings |
|
| any field |
|
| any field |
|
Since 2.14, a non-positive multiple_of raises an error when the model is defined instead of failing at validation time.
A field is required unless it has a default, so shipped_on: date | None = None is optional. Without the = None, the same field is required but accepts None, which trips people coming from V1.
For a fixed set of strings, Literal["pending", "paid", "shipped"] is the lightest option, as the error above shows. An Enum works the same way when you also need the values elsewhere in your code.
Types and constraints cover shape. Validators cover business rules, such as "check-out must be after check-in."
The validators docs define four modes:
Mode | Runs | Receives | Use it for |
|---|---|---|---|
| after Pydantic's own validation | the typed value | normalizing or checking a parsed value |
| before parsing and coercion | the raw input (any type) | reshaping input, such as splitting a string |
| instead of Pydantic's validation | the raw input | full custom parsing; no type check follows |
| around Pydantic's validation | the raw input and a handler | try, fall back, or short-circuit |
After validators are the default because they only see values that already match the type.
This booking model uses all three common hooks: an after validator to normalize the email, a before validator to accept a comma-separated string for tags, and an after model validator to compare two fields.
from datetime import date
from typing import Any
from pydantic import BaseModel, ValidationError, field_validator, model_validator
class Booking(BaseModel):
guest_email: str
tags: list[str]
check_in: date
check_out: date
@field_validator("guest_email")
@classmethod
def normalize_email(cls, value: str) -> str:
if "@" not in value:
raise ValueError("must contain @")
return value.strip().lower()
@field_validator("tags", mode="before")
@classmethod
def split_tags(cls, value: Any) -> Any:
if isinstance(value, str):
return [tag.strip() for tag in value.split(",")]
return value
@model_validator(mode="after")
def check_dates(self) -> "Booking":
if self.check_out <= self.check_in:
raise ValueError("check_out must be after check_in")
return self
booking = Booking(
guest_email=" [email protected] ",
tags="late-arrival, sea-view",
check_in="2027-03-01",
check_out="2027-03-04",
)
print(booking.guest_email, booking.tags)
for data in (
{"guest_email": "ada", "tags": [], "check_in": "2027-03-04", "check_out": "2027-03-01"},
{"guest_email": "[email protected]", "tags": [], "check_in": "2027-03-04", "check_out": "2027-03-01"},
):
try:
Booking(**data)
except ValidationError as exc:
print([(error["loc"], error["msg"]) for error in exc.errors()])[email protected] ['late-arrival', 'sea-view']
[(('guest_email',), 'Value error, must contain @')]
[((), 'Value error, check_out must be after check_in')]In the first failure the dates are also wrong, yet only the email error appears. An after model validator runs on a validated instance, so when any field fails, it never runs. Fix the email and the date rule fires, with an empty location because it belongs to the whole model.
The @classmethod line under @field_validator follows the pattern in the docs' own examples. Our Python decorators guide explains how stacked decorators apply from the bottom up.
Validation brings data in. Serialization sends it out, and Pydantic gives you control over names, fields, and derived values.
from pydantic import BaseModel, ConfigDict, Field, computed_field
from pydantic.alias_generators import to_camel
class Invoice(BaseModel):
model_config = ConfigDict(
alias_generator=to_camel, validate_by_name=True, validate_by_alias=True
)
invoice_id: int
net_amount: float
vat_rate: float = 0.21
internal_note: str | None = Field(default=None, exclude=True)
@computed_field
@property
def gross_amount(self) -> float:
return round(self.net_amount * (1 + self.vat_rate), 2)
invoice = Invoice.model_validate({"invoiceId": 7, "netAmount": 100, "internalNote": "VIP"})
print(invoice.model_dump())
print(invoice.model_dump(by_alias=True, exclude={"vat_rate"}))
print(invoice.model_dump_json(by_alias=True)){'invoice_id': 7, 'net_amount': 100.0, 'vat_rate': 0.21, 'gross_amount': 121.0}
{'invoiceId': 7, 'netAmount': 100.0, 'grossAmount': 121.0}
{"invoiceId":7,"netAmount":100.0,"vatRate":0.21,"grossAmount":121.0}Four things happened. The alias generator matched camelCase input to snake_case fields, and internal_note was accepted but never serialized because it sets exclude=True. gross_amount is a computed field, so it appears in every dump without being an input. And model_dump_json() returned a JSON string directly, with no json.dumps() step.
Lax mode suits inputs that arrive as strings, such as URL parameters, HTTP headers, and environment variables, which the strict mode docs list as cases where coercion is useful. For payments or internal events, you may want "1999" to be rejected instead of becoming 1999.
from pydantic import BaseModel, ConfigDict, ValidationError
class Payment(BaseModel):
amount_cents: int
currency: str
class StrictPayment(BaseModel):
model_config = ConfigDict(strict=True)
amount_cents: int
currency: str
print(Payment(amount_cents="1999", currency="EUR"))
try:
StrictPayment(amount_cents="1999", currency="EUR")
except ValidationError as exc:
print(exc.errors()[0]["type"])
print(StrictPayment.model_validate_json('{"amount_cents": 1999, "currency": "EUR"}'))amount_cents=1999 currency='EUR'
int_type
amount_cents=1999 currency='EUR'Strict mode can be set for a whole model, as here, for one field with Field(strict=True), or for one call with model_validate(data, strict=True). The strict mode docs note that looser rules apply to JSON input: date and time types still accept strings in strict mode, because JSON has no date type.
Not everything needs a class. TypeAdapter validates any type, and every model can describe itself as JSON Schema.
import json
from typing import Annotated
from pydantic import Field, TypeAdapter
Scores = TypeAdapter(list[Annotated[int, Field(ge=0, le=100)]])
print(Scores.validate_python(["90", 75, 100]))
print(Scores.validate_json("[1, 2, 3]"))
print(json.dumps(Scores.json_schema()))[90, 75, 100]
[1, 2, 3]
{"items": {"maximum": 100, "minimum": 0, "type": "integer"}, "type": "array"}TypeAdapter replaces the V1 helpers parse_obj_as and schema_of, per the migration guide. Create it once at module level, a point the performance section below measures.
import json
from typing import Literal
from pydantic import BaseModel, Field
class Product(BaseModel):
"""A product in the catalog."""
sku: str = Field(description="Stock keeping unit")
price: float = Field(gt=0)
status: Literal["draft", "live"] = "draft"
print(json.dumps(Product.model_json_schema(), indent=2)){
"description": "A product in the catalog.",
"properties": {
"sku": {
"description": "Stock keeping unit",
"title": "Sku",
"type": "string"
},
"price": {
"exclusiveMinimum": 0,
"title": "Price",
"type": "number"
},
"status": {
"default": "draft",
"enum": [
"draft",
"live"
],
"title": "Status",
"type": "string"
}
},
"required": [
"sku",
"price"
],
"title": "Product",
"type": "object"
}The docstring became the description, gt=0 became exclusiveMinimum, and only fields without defaults are required. FastAPI's home page says it is based on the OpenAPI and JSON Schema standards, which is why a Pydantic model doubles as API documentation there.
pydantic-settings is a separate package with one main class, BaseSettings. Per the settings docs, a BaseSettings model fills any field you did not pass by reading the environment.
This script writes a throwaway .env file, sets two environment variables, and shows which value wins.
import os
from pathlib import Path
from pydantic import BaseModel, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
class Database(BaseModel):
host: str = "localhost"
port: int = 5432
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_prefix="APP_", env_file=".env", env_nested_delimiter="__"
)
debug: bool = False
api_key: SecretStr
workers: int = 2
db: Database = Database()
Path(".env").write_text("APP_API_KEY=sk-from-dotenv\nAPP_WORKERS=4\n")
os.environ["APP_WORKERS"] = "8"
os.environ["APP_DB__PORT"] = "6543"
settings = Settings()
print(settings.workers, settings.db.port, settings.debug)
print(settings.api_key)
print(settings.api_key.get_secret_value())
print(Settings(workers=1).workers)8 6543 False
**********
sk-from-dotenv
1APP_WORKERS=8 in the environment beat APP_WORKERS=4 in .env. The init argument workers=1 beat both. `APP_DBPORT reached the nested model because of env_nested_delimiter="". SecretStr printed as stars, so the key stays out of logs and tracebacks until you call get_secret_value()`.
The docs list the field value priority from highest to lowest:
Priority | Source |
|---|---|
1 | CLI arguments, if |
2 | Arguments passed to the |
3 | Environment variables |
4 | Variables from a dotenv ( |
5 | Variables from the secrets directory |
6 | Field defaults |
Two defaults differ from BaseModel. Environment variable names are case-insensitive unless you set case_sensitive=True, and BaseSettings validates default values, which a plain model does not.
The performance tips page opens with "In most cases Pydantic won't be your bottleneck." When it is, two of its tips take a minute to check: parse JSON inside Pydantic, and build each TypeAdapter once.
# Timings vary by machine; the ratios are the point.
import json
import timeit
from pydantic import BaseModel, TypeAdapter
class Event(BaseModel):
id: int
user: str
score: float
tags: list[str]
payload = json.dumps(
[{"id": i, "user": f"user{i}", "score": i / 3, "tags": ["a", "b"]} for i in range(10_000)]
)
Events = TypeAdapter(list[Event])
reused = TypeAdapter(list[int])
def two_step():
return Events.validate_python(json.loads(payload))
def one_step():
return Events.validate_json(payload)
def rebuild_adapter():
return TypeAdapter(list[int]).validate_python([1, 2, 3])
def reuse_adapter():
return reused.validate_python([1, 2, 3])
def best_ms(func, number):
return min(timeit.repeat(func, number=number, repeat=5)) / number * 1000
a, b = best_ms(two_step, 20), best_ms(one_step, 20)
c, d = best_ms(rebuild_adapter, 200), best_ms(reuse_adapter, 200)
print(f"json.loads + validate_python: {a:.2f} ms")
print(f"validate_json: {b:.2f} ms ({a / b:.1f}x faster)")
print(f"new TypeAdapter per call: {c:.4f} ms")
print(f"reused TypeAdapter: {d:.4f} ms ({c / d:.0f}x faster)")json.loads + validate_python: 10.78 ms
validate_json: 6.87 ms (1.6x faster)
new TypeAdapter per call: 0.0137 ms
reused TypeAdapter: 0.0003 ms (54x faster)On an 8-vCPU Intel Xeon server, validate_json() was 1.6x to 1.7x faster than json.loads() plus validation for 10,000 events across five runs. A reused TypeAdapter was 53x to 58x faster than one built inside the function. The docs explain the second result: "Each time a TypeAdapter is instantiated, it will construct a new validator and serializer."
The JSON result has an exception. The docs say a before or wrap model validator can make the two-step method faster, so measure your own models before you rewrite a hot path.
Building a model class has a cost too, paid at import time. The 2.14 announcement lists schema generation optimizations that "individually reduce model build time by 5–20% on our benchmarks," which matters for applications with hundreds of models. 2.14 also moved Fraction, named tuples, deque, OrderedDict, and Counter to native Rust schemas, replacing slower Python validators.
A few 2.14 changes alter output your code might read. The release notes call them minor changes that are "considered non-breaking changes according to our versioning policy."
MISSING marks a field that was never provided, which is different from a field set to None. It was experimental in 2.12 and is now part of the main API, per the 2.14 announcement. That makes PATCH-style updates clean:
from pydantic import MISSING, BaseModel
class Patch(BaseModel):
title: str | MISSING = MISSING
timeout: int | None | MISSING = MISSING
patch = Patch(timeout=None)
print(patch.model_dump())
print(patch.title is MISSING)
print(Patch.model_json_schema()["properties"]["timeout"]){'timeout': None}
True
{'anyOf': [{'type': 'integer'}, {'type': 'null'}], 'title': 'Timeout'}title was never sent, so it is left out of the dump. timeout was sent as None, so it stays. The sentinel does not appear in the JSON Schema. Static checkers support it from pyright 1.1.414 and mypy 2.4, per the same announcement; our mypy vs pyright comparison covers both.
Before 2.14, Pydantic could add keys to model_config, such as values derived from deprecated settings. Now it only holds what you set, merged with parent classes:
from pydantic import BaseModel
class Base(BaseModel):
model_config = {"title": "MyBase"}
class Model(Base):
model_config = {"populate_by_name": True}
print(Model.model_config){'title': 'MyBase', 'populate_by_name': True}On 2.13 the same print also showed validate_by_alias and validate_by_name, per the announcement. Code that read those keys from model_config needs a change. Other 2.14 changes include support for Python 3.15 lazy imports and TypeForm, and removal of the regex pattern from Decimal JSON Schema by default.
With V1 support over after 1.10.27, the migration is no longer optional for maintained code. The migration guide points to the bump-pydantic codemod for the mechanical part. These renames cover most V1 code:
Pydantic V1 | Pydantic V2 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The old method names still run on 2.14.4, with a warning:
import warnings
from pydantic import BaseModel
class Point(BaseModel):
x: int
y: int
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
Point(x=1, y=2).dict()
print(type(caught[0].message).__name__)
print(caught[0].message.message)PydanticDeprecatedSince20
The `dict` method is deprecated; use `model_dump` insteadRun your test suite with -W error::DeprecationWarning to turn these warnings into failures and find every call site. A beginner's guide ranking near the top for "pydantic python" on 5 December 2026 still taught dict() and parse_obj(), so check the date on any tutorial you copy from.
A stdlib dataclass stores whatever you give it. A Pydantic model validates it.
from dataclasses import dataclass
from pydantic import BaseModel
@dataclass
class PlainPoint:
x: int
y: int
class Point(BaseModel):
x: int
y: int
print(PlainPoint(x="1", y="oops"))
print(Point(x="1", y="2"))PlainPoint(x='1', y='oops')
x=1 y=2
| Pydantic | |
|---|---|---|
Validates types at runtime | No | Yes, lax by default |
Coerces | No | Yes, unless strict |
JSON parse and dump | No (use |
|
JSON Schema | No |
|
Install | Standard library |
|
Developers on Reddit draw the line at the boundary: one r/Python commenter said "pydantic is best at the edges of your app," such as validating a request. For structures in between, the same commenter suggested dataclasses plus type checking. Another said Pydantic "made the type control on system boundaries insanely simple" and now defines a model for every third-party API response they expect.
If you want validation with dataclass syntax, Pydantic offers pydantic.dataclasses.dataclass. The dataclasses docs say these "are not a replacement for Pydantic models."
.dict(), parse_obj(), @validator, and class Config all come from V1. They raise deprecation warnings today and V1 itself gets no more releases after 1.10.27. Use the rename table above.
An after @model_validator never runs when a field fails, as the booking example showed. If users must see cross-field errors in the same response, use a before model validator or check the fields in your handler.
Model.model_validate(json.loads(text)) parses in Python first. Model.model_validate_json(text) does both steps in Rust and ran about 1.6x faster in our test.
A TypeAdapter built per call rebuilt its validator every time and ran about 50x slower than a module-level one. Create it once and reuse it.
api_key: str prints the key in every log line that prints the settings object. Use SecretStr and call get_secret_value() only where you send the key.

Learn FastAPI with code tested on 0.165.2: endpoints, Pydantic models, dependency injection, the async def trap, tests, body limits, and deployment.

Learn Plotly in Python with tested code: Plotly Express, graph objects, HTML and PNG export, Dash and Streamlit, plus what changed in plotly 7.

Learn seaborn with tested code: tidy data, axes-level vs figure-level plots, heatmaps, the objects API, and how 0.13.2 runs on pandas 3 and Matplotlib 3.11.