Pynions

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.

Updated 13 min read
Python logo on a white rounded tile against a blue background

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.

Key Takeaways

  • Pydantic models coerce input by default: the string "42" becomes the integer 42. Turn on strict mode when a wrong type should fail instead.
  • Field validators come in four modes (after, before, plain, wrap). Start with after validators, which the docs call "generally more type safe."
  • Parse JSON with 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.
  • Load configuration with pydantic-settings. Init arguments beat environment variables, which beat a .env file, which beats the defaults.
  • Pydantic 1.10.27 (29 October 2026) is the last V1 release. Any tutorial that calls .dict() or parse_obj() is teaching the old API.

What Is Pydantic?

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 Validation documentation home page for version 2.14.4

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.

Why Pydantic Matters in 2027

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."

How Pydantic Works: Install, Models, and Errors

Start with three steps: install it, define a model, and read the errors it raises.

Install Pydantic 2.14.4

Shell
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__)"
Text
2.14.4 2.16.4

PyPI 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.

Your First Pydantic Model

A model is a class with annotated fields. This one takes strings for every field and shows what Pydantic does with them.

Python
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"])
Text
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.

Read a Validation Error

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.

Python
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)
Text
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_than

Each 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.

Pydantic Fields: Types, Constraints, and Defaults

Annotations set the type. Field() adds constraints, defaults, aliases, and documentation on top.

Constraints With Field and Annotated

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

gt, ge, lt, le

numbers

Field(gt=0)

multiple_of

numbers

Field(multiple_of=5)

min_length, max_length

strings, lists

Field(max_length=280)

pattern

strings

Field(pattern=r"^[A-Z]{3}$")

default, default_factory

any field

Field(default_factory=list)

alias, validation_alias

any field

Field(alias="userId")

Since 2.14, a non-positive multiple_of raises an error when the model is defined instead of failing at validation time.

Optional Fields and Literal Values

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.

Pydantic Validators: Field and Model Rules

Types and constraints cover shape. Validators cover business rules, such as "check-out must be after check-in."

The Four Field Validator Modes

The validators docs define four modes:

Mode

Runs

Receives

Use it for

after (default)

after Pydantic's own validation

the typed value

normalizing or checking a parsed value

before

before parsing and coercion

the raw input (any type)

reshaping input, such as splitting a string

plain

instead of Pydantic's validation

the raw input

full custom parsing; no type check follows

wrap

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.

A Field Validator and a Model Validator

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.

Python
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()])
Text
[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.

Serialization: model_dump, JSON, and Computed Fields

Validation brings data in. Serialization sends it out, and Pydantic gives you control over names, fields, and derived values.

Python
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))
Text
{'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.

Strict Mode: When Coercion Is a Bug

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.

Python
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"}'))
Text
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.

TypeAdapter and JSON Schema

Not everything needs a class. TypeAdapter validates any type, and every model can describe itself as JSON Schema.

Validate a Type Without a Model

Python
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()))
Text
[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.

Generate JSON Schema From a Model

Python
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))
Text
{
  "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: Configuration From Environment Variables

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.

Load Settings From env Vars and a .env File

This script writes a throwaway .env file, sets two environment variables, and shows which value wins.

Python
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)
Text
8 6543 False
**********
sk-from-dotenv
1

APP_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()`.

Settings Source Priority

The docs list the field value priority from highest to lowest:

Priority

Source

1

CLI arguments, if cli_parse_args is enabled

2

Arguments passed to the Settings initializer

3

Environment variables

4

Variables from a dotenv (.env) file

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.

Pydantic Performance: What the Rust Core Buys You

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.

Python
# 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)")
Text
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.

Faster Model Builds in 2.14

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.

What Changed in Pydantic 2.14

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."

The MISSING Sentinel Is Stable

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:

Python
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"])
Text
{'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.

model_config No Longer Changes Behind Your Back

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:

Python
from pydantic import BaseModel


class Base(BaseModel):
    model_config = {"title": "MyBase"}


class Model(Base):
    model_config = {"populate_by_name": True}


print(Model.model_config)
Text
{'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.

Migrating From Pydantic V1

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

Model.parse_obj(data)

Model.model_validate(data)

Model.parse_raw(text)

Model.model_validate_json(text)

model.dict()

model.model_dump()

model.json()

model.model_dump_json()

model.copy()

model.model_copy()

Model.schema()

Model.model_json_schema()

Model.construct()

Model.model_construct()

Model.update_forward_refs()

Model.model_rebuild()

parse_obj_as(T, data)

TypeAdapter(T).validate_python(data)

@validator / @root_validator

@field_validator / @model_validator

class Config: orm_mode = True

model_config = ConfigDict(from_attributes=True)

The old method names still run on 2.14.4, with a warning:

Python
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)
Text
PydanticDeprecatedSince20
The `dict` method is deprecated; use `model_dump` instead

Run 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.

Pydantic vs dataclasses

A stdlib dataclass stores whatever you give it. A Pydantic model validates it.

Python
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"))
Text
PlainPoint(x='1', y='oops')
x=1 y=2


dataclasses.dataclass

Pydantic BaseModel

Validates types at runtime

No

Yes, lax by default

Coerces "1" to 1

No

Yes, unless strict

JSON parse and dump

No (use json yourself)

model_validate_json, model_dump_json

JSON Schema

No

model_json_schema()

Install

Standard library

pip install pydantic

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."

Common Pydantic Mistakes to Avoid

Copying a V1 Tutorial Into V2 Code

.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.

Expecting a Model Validator to Report Field Errors Too

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.

Parsing JSON Twice

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.

Building a TypeAdapter Inside a Function

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.

Leaving Secrets as Plain Strings

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.

Frequently Asked Questions

Sources

Related Articles