Pydantic Tutorial
Learn Pydantic step by step: 38 lessons in 9 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What Is Pydantic? Learn what Pydantic does, why Python needs data validation, how type hints become checks, and where the library fits in real projects such as APIs and settings.
- Your First Pydantic Model Create a Pydantic BaseModel, set field types, defaults and required fields, read attributes, validate dicts and JSON, and understand how models behave like objects.
- How Pydantic Validation Works Understand what Pydantic does when it validates input: conversion rules, lax versus strict mode, extra keys, field order, and why models validate on creation.
- Model Methods: Dump, Copy and Fields A practical tour of the Pydantic v2 model API: model_dump, model_dump_json, model_copy, model_fields, model_fields_set, model_construct and equality, plus v1 name mapping.
Models and Types
- Field Types in Pydantic A tour of the types Pydantic understands: numbers, strings, bytes, dates and times, Decimal, UUID, Path, Enum and more, with parsing rules and runnable examples.
- Optional Fields and Defaults Learn the difference between required, optional and nullable fields in Pydantic, how to set defaults, use default_factory, and avoid the mutable default trap.
- Nested Models and Collections Validate lists, dicts, sets and tuples in Pydantic, nest models inside models, handle self-referencing trees with forward references, and read error locations.
- Unions, Literals and Discriminated Unions Accept several types with unions, restrict values with Literal, understand smart mode matching, and use discriminated unions for fast, clear validation of tagged data.
- Model Inheritance and Generic Models Reuse fields with model inheritance, share configuration across a project with a base model, and write generic Pydantic models such as Page[T] and ApiResponse[T].
Validation and Constraints
- Field Constraints with Field() Add rules to fields with Pydantic Field(): numeric bounds, string length, regex patterns, collection sizes, decimal digits, multiple_of, titles and descriptions.
- Annotated and Reusable Constrained Types Build reusable constrained types with typing.Annotated, use PositiveInt, conint and StringConstraints, put constraints on list items, and keep rules in one place.
- Validation Errors in Detail Read and handle Pydantic ValidationError: the errors() structure, loc paths, error types, error_count, JSON output, custom messages and turning errors into friendly text.
- Strict Mode and Coercion Control how much Pydantic converts input. Compare lax and strict mode, enable strict per field, per model, per call or with StrictInt, and learn the JSON exception.
- Validating Special Types: Email, URL, Secrets Use Pydantic's built-in special types: EmailStr, HttpUrl, AnyUrl, SecretStr, IP addresses, PastDate, AwareDatetime, ByteSize and Json, with the pitfalls of each.
Serialization
- Dumping to Dicts and JSON Master Pydantic serialization: python and json modes, include and exclude (including nested fields), exclude_unset, exclude_none, indent, round trips and field-level exclude.
- Aliases and Naming Conventions Map JSON keys to Python field names with Pydantic aliases: alias, validation_alias, serialization_alias, populate_by_name, AliasPath and alias generators for camelCase APIs.
- Computed Fields and Custom Serializers Add derived values to output with computed_field, change how a field is written with field_serializer, reshape whole models with model_serializer and use PlainSerializer.
- JSON Schema Generation Generate JSON Schema from Pydantic models with model_json_schema, read $defs and required, add titles and examples, use json_schema_extra and understand modes and use cases.
- TypeAdapter, Dataclasses and TypedDict Validate and serialize any Python type without a model using TypeAdapter, add validation to standard dataclasses and TypedDict, and choose between models and dataclasses.
Settings and Config
- Settings Management with BaseSettings Load typed application settings from environment variables with pydantic-settings. Learn BaseSettings, defaults, type coercion, required values and clear startup errors.
- Settings Sources and .env Files Control where Pydantic settings come from. Use env_prefix, aliases, nested delimiters, .env files, secrets directories and a custom order of sources.
- ConfigDict: Model Configuration Options Change how a Pydantic model behaves with ConfigDict. Learn extra, frozen, strict, validate_assignment, str_strip_whitespace, alias_generator and from_attributes.
- Secrets and Settings Patterns Handle passwords and API keys safely with SecretStr, build settings once with a cached function, override them in tests and keep dev and production values apart.
Custom Validators and Types
- Custom Field Validators Write your own checks with @field_validator. Learn after and before modes, ValidationInfo, validating several fields, raising good errors and common mistakes.
- Custom Model Validators Validate relationships between fields with @model_validator. Learn after, before and wrap modes, checking date ranges, either-or fields and rewriting input data.
- Annotated Validators and Reusable Types Build reusable types with Annotated and AfterValidator, BeforeValidator, PlainValidator and WrapValidator, so one rule can be shared by many fields and models.
- Custom Types and Validation Context Create your own Pydantic types with __get_pydantic_core_schema__, control JSON Schema and serialization, and pass runtime data to validators with the context argument.
Integration with FastAPI
- FastAPI Request Models with Pydantic See how FastAPI uses Pydantic models to validate request bodies, query parameters and nested JSON, return 422 errors and generate OpenAPI documentation automatically.
- FastAPI Response Models Control what a FastAPI endpoint returns with response_model. Hide private fields, shape lists, exclude unset values, use inheritance for input and output models and set status codes.
- FastAPI Errors, Dependencies and Settings Customize FastAPI's 422 error format, share validated parameters with Depends, inject BaseSettings and override dependencies in tests, all with Pydantic models.
Performance and Patterns
- TypeAdapter and validate_call Validate any Python type without a model using TypeAdapter, and check function arguments and return values with @validate_call. Includes JSON, schemas and reuse.
- Pydantic Performance Tips Make Pydantic fast. Learn validate_json, reusing TypeAdapter, tagged unions, avoiding repeated validation, model_construct, strict mode and how to measure before tuning.
- Generic and Recursive Models Write reusable Pydantic models with Generic and TypeVar, such as paged responses, and model trees with self-referencing and forward references, plus how to handle depth limits.
- Testing and Design Patterns with Pydantic Test Pydantic models, validators and settings with clear, small tests. Learn factories, parametrized cases, error assertions, DTO and repository patterns and schema versioning.
Projects and Practice
- Project: A Configuration Loader Build a configuration loader step by step: nested typed settings, TOML file plus environment overrides, secrets, production rules, readable startup errors and tests.
- Project: A Validated Bookshelf API Build a small FastAPI service with Pydantic: create, list, filter and patch books, separate input and output models, consistent errors, pagination and tests through httpx.
- Project: A Validating CSV Importer Build a CSV importer with Pydantic: clean messy cells, validate every row, collect errors with line numbers, process in chunks, and write a clear import report.
- Practice: Pydantic Exercises Six hands-on Pydantic exercises with runnable starter code and full solutions: constraints, validators, settings, discriminated unions, serialization and a mini-API model.