Defining a model
Inherit fromBaseModel and declare fields using Python type annotations:
User has a name (string), an email (string), and an age (integer). That’s it. No __init__ method, no boilerplate.
Type annotations are not just documentation here — Pydantic reads them at runtime and uses them to validate data. Missing a type annotation means Pydantic ignores the field entirely.
Pydantic vs Python dataclasses
You may have seen Python’s built-indataclass decorator. It looks similar:
- dataclass (no validation)
- Pydantic BaseModel (validated)
__init__ method from your type hints but perform no validation at all — the hints are pure documentation. Pydantic enforces them at runtime. For most projects, reach for Pydantic directly: you get validation, serialization, and JSON Schema generation with almost no extra effort.
Creating instances
Pass your data as keyword arguments:User(...). If anything is wrong, you get a ValidationError right there — not somewhere downstream in your code.
Automatic type coercion
Pydantic is smart about compatible types. If a value can be safely converted to the declared type, it will be:Handling validation errors
When data is invalid, Pydantic raises aValidationError with a precise message:
Required vs optional fields
Fields with no default value are required. Fields with a default are optional:Default values
Set a default for fields that usually have a common value:Converting a model to a dictionary
Usemodel_dump() to export a model’s data as a plain Python dictionary:
model_dump() constantly — when storing data in a database, sending it to another service, or logging it.
Converting a model to JSON
Usemodel_dump_json() to get a JSON-encoded string:
Creating a model from a dictionary
When you receive data as a dictionary (from an API response, a database row, or a parsed JSON file), you have two equally valid ways to create a model:**data for everyday use and model_validate() when you need options like strict=True.
Using models as type hints
Pydantic models work naturally as type hints in function signatures, giving you IDE autocomplete and making your intent clear:user: User communicates exactly what data it needs.
Strict mode
By default, Pydantic coerces compatible types. If you need exact-type matching, enable strict mode:ConfigDict is a special configuration object Pydantic looks for on the model_config class attribute. For most use cases, the default lax mode is what you want.
Real-world example: parsing an API response
Real-world example: parsing an API response
Learn more
What’s next?
You can now create and instantiate basic models. Next, you’ll learn how to add constraints to fields — minimum lengths, numeric ranges, regex patterns, and custom validation logic.Validation and Fields
Learn how to add validation rules and constraints to your Pydantic fields.