Skip to content
Tutorials Center
My learning

Topics

Lesson 1 of 38 ยท 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.

Every program receives data it did not create: JSON from a web request, rows from a spreadsheet, values typed into a form, environment variables, a config file. That data is often wrong in small ways. A number arrives as the string "42", a field is missing, an email has no @. Python does not complain about any of this until a calculation fails ten functions later, far away from the real cause.

Pydantic is a Python library that checks data at the door. You describe the shape of the data with ordinary type hints, and Pydantic turns raw input into clean, correctly typed Python objects, or raises a clear error that says exactly which field is wrong and why. It is one of the most downloaded Python packages and the validation engine behind FastAPI, many LLM toolkits, and countless configuration systems.

This tutorial covers Pydantic v2, the current major version. Its core is written in Rust, which makes it fast, while the API you use stays pure Python.

The problem Pydantic solves

Imagine a function that receives a user as a dictionary:

Python Dictionaries trust everything

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second call fails with a TypeError because "36" + 1 is not valid. Type hints such as dict or even int do not help, because Python does not enforce type hints at runtime. They are notes for people and tools. Pydantic is the missing piece that makes the hints do real work.

The same idea with Pydantic

You describe the data as a class that inherits from BaseModel. Each attribute has a type. When you create an instance, Pydantic validates the input against those types.

Python Your first validated data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The string "36" was parsed into the integer 36. After construction you can trust the types: user.age is really an int. If something cannot be converted, you get a ValidationError instead of a half-broken object (more on that in Validation Errors).

Pydantic is about parsing, not only checking. It converts input into the type you asked for when that is safe and unambiguous, and rejects it otherwise. You can turn conversion off with strict mode.

What happens inside

flowchart LR
    A["Raw input<br/>dict, JSON, kwargs"] --> B["Pydantic core<br/>(Rust)"]
    B -->|valid| C["Typed model instance"]
    B -->|invalid| D["ValidationError<br/>with every problem"]
    C --> E["Use it: attributes,<br/>dump to dict or JSON"]

Input goes in, and either a trustworthy object or a complete list of problems comes out.

Notice that Pydantic reports all the problems in one go, not just the first. That is very useful when you show errors to a user filling in a form or to an API client.

Python All errors at once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three problems are reported together: name is not a string, price is not a number, and in_stock is missing.

Where Pydantic is used

  • Web APIs. FastAPI uses Pydantic models for request bodies, query parameters and responses, and generates documentation from them. See Integration with FastAPI (later in this tutorial, see the track page).
  • Configuration. The companion package pydantic-settings reads environment variables and .env files into a validated settings object.
  • Data pipelines. Validate rows from CSV files, databases or message queues before they reach your business logic.
  • LLM applications. Describe the JSON an AI model should return, then validate what it actually returned.
  • Plain scripts. Anywhere you would otherwise write if not isinstance(...) checks by hand.

Pydantic compared with other tools

Tool What it gives you Validates at runtime?
Type hints only Documentation and editor help; mypy checks code statically No
dataclasses A class with generated __init__, no checks No
attrs Like dataclasses with optional validators you write Only what you add
Pydantic Types become validation and conversion rules, plus serialization and JSON Schema Yes, automatically

Pydantic models also work well with static type checkers and editors: because the fields are real annotated attributes, autocompletion and mypy understand them.

How to install it

On your own computer:

Terminal
pip install pydantic

Optional extras are separate packages you will meet later: email-validator for email addresses, and pydantic-settings for settings management. Code on this site runs in your browser with Pydantic already available, so you can simply press Run.

Use a virtual environment (python -m venv .venv) per project so each project pins its own Pydantic version.

A tour of what you will learn

Describe data with types

Models Classes with typed fields
Types int, str, lists, unions
1 / 4

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do plain Python type hints not protect a function from bad input?

    Annotations are metadata. Python stores them but never checks them. Pydantic reads them and performs the checks for you.
  2. 2. What does Pydantic do with User(name='Grace', age='36') when age is declared as int?

    In the default (lax) mode Pydantic converts values when the conversion is safe. The string '36' becomes the int 36.
  3. 3. If a model has three invalid fields, how many problems does the ValidationError report?

    Pydantic collects every problem and reports them together, which makes it easy to show complete feedback to a user or API client.
  4. 4. Which class do you inherit from to create a Pydantic model?

    Models are subclasses of BaseModel.

Summary

  • Pydantic validates and converts data using Python type hints; Python itself never enforces them at runtime.
  • You declare a class that inherits from BaseModel; creating an instance runs validation.
  • Valid input becomes a correctly typed object; invalid input raises a ValidationError listing every problem.
  • It is used for APIs (FastAPI), settings, data pipelines and LLM output checking.
  • This tutorial teaches Pydantic v2, whose core is written in Rust.

Next: Your First Pydantic Model