> ## Documentation Index
> Fetch the complete documentation index at: https://fastapi2day.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Pydantic Introduction: Runtime Data Validation in Python

> Learn what Pydantic is, why Python's dynamic typing creates real-world bugs, and how Pydantic solves them with runtime validation and type safety.

Python's flexibility is one of its greatest strengths — but it can also be one of its biggest liabilities when you're building production applications. Because Python is dynamically typed, variables can hold any value at any time, and the language won't complain. The moment your code starts consuming data from the outside world — an HTTP request, a database record, a third-party API, an environment variable — you lose all guarantees about what shape that data is in. Pydantic bridges that gap by letting you declare the structure and types of your data as Python classes, then validating incoming data against those declarations at runtime, immediately and loudly, before bad data can propagate silently through your application.

## The problem with Python's dynamic typing

Python lets you reassign a variable to any type at any point:

```python theme={null}
age = 25
age = "twenty-five"
age = [25, None, "unknown"]
```

No errors. Python doesn't care. For quick scripts this is fine, but the moment you're processing external data you have a problem.

Consider a simple API handler:

```python theme={null}
def create_user(data: dict):
    user_id = data["id"]
    email   = data["email"]
    age     = data["age"]

    # Works only if age is actually an int
    birth_year = 2025 - age
```

You expect:

```json theme={null}
{"id": 1, "email": "dave@example.com", "age": 25}
```

But the caller sends:

```json theme={null}
{"id": 1, "email": null, "age": "unknown"}
```

Your code crashes — or worse, silently produces garbage data that reaches your database.

<Warning>
  Without validation, data bugs often hide until production. By the time you notice, corrupted data may already be persisted.
</Warning>

## Where bad data comes from

You're constantly working with untrusted or weakly typed data sources:

* **API responses** — external services return whatever they want
* **User input** — form fields and query parameters are always strings
* **Configuration** — environment variables are always strings, even `PORT=8000`
* **Database records** — nullable columns, schema migrations, and legacy data can leave fields missing or malformed

## What Pydantic does

Pydantic lets you describe the shape of your data as a class, then validates incoming data against that description at runtime. If validation fails, you get a precise error message immediately — at the boundary where data enters your system, not three call-stack layers later.

```python theme={null}
from pydantic import BaseModel

class User(BaseModel):
    id: int
    email: str
    age: int

# Valid data — works fine
user = User(id=1, email="dave@example.com", age=25)
print(user.age)   # 25
print(type(user.age))  # <class 'int'>

# Invalid data — fails immediately
user = User(id=1, email=None, age="unknown")
```

The second instantiation raises a clear error:

```text theme={null}
2 validation errors for User
email
  Input should be a valid string [type=string_type]
age
  Input should be a valid integer, unable to parse string as an integer [type=int_parsing]
```

The problem is caught at the source, not in production.

<Note>
  Pydantic also performs **type coercion** for compatible types — for example, the string `"25"` is automatically converted to the integer `25`. You'll learn exactly when this happens in the next page.
</Note>

## Why Pydantic matters for AI and FastAPI

Pydantic is the backbone of the modern Python ecosystem:

<Steps>
  <Step title="FastAPI">
    FastAPI uses Pydantic models to validate every incoming request body and outgoing response. Define a model, and FastAPI handles the rest — including auto-generated API docs.
  </Step>

  <Step title="AI frameworks">
    LangChain, OpenAI's Python SDK, and most AI orchestration tools use Pydantic to define structured outputs from language models. When an agent calls a tool or returns a result, Pydantic ensures the data is what you expect.
  </Step>

  <Step title="Configuration management">
    `pydantic-settings` extends Pydantic to load and validate environment variables, `.env` files, and secrets — replacing fragile `os.getenv()` calls with a typed, validated settings class.
  </Step>

  <Step title="Agentic coding">
    When you define clear Pydantic models, AI coding assistants understand your data structures far better. Well-defined models act as guardrails that guide both humans and AI toward correct usage.
  </Step>
</Steps>

<Tip>
  If you're planning to work with FastAPI, LangChain, SQLModel, or any modern Python framework, you'll encounter Pydantic constantly. Investing time here pays dividends across everything you build.
</Tip>

## A quick preview

Here's the pattern you'll be writing throughout this course:

```python theme={null}
from pydantic import BaseModel, Field

class User(BaseModel):
    id: int
    name: str
    email: str
    age: int = Field(ge=0, le=120)

user = User(id=1, name="Alice", email="alice@example.com", age=25)
print(user.model_dump())
# {'id': 1, 'name': 'Alice', 'email': 'alice@example.com', 'age': 25}
```

You declare a model, Pydantic enforces it, and you work with clean, typed data from that point on.

## Installation

Install Pydantic using `pip` or `uv`:

```bash theme={null}
pip install pydantic
```

```bash theme={null}
uv add pydantic
```

Verify the installation:

```python theme={null}
import pydantic
print(pydantic.__version__)  # e.g. 2.7.1
```

<Accordion title="Which version of Pydantic does this course use?">
  This course uses **Pydantic v2**, the current major release. Pydantic v2 was rewritten in Rust and is significantly faster than v1. If you encounter older tutorials using `.dict()` instead of `.model_dump()`, they are using Pydantic v1. The core concepts are the same, but the method names differ.
</Accordion>

## Learn more

* [Official Pydantic documentation](https://docs.pydantic.dev/latest/)
* [Pydantic on GitHub](https://github.com/pydantic/pydantic)

***

## What's next?

Now that you understand the problem Pydantic solves, it's time to write your first model.

<Card title="Your First Model" icon="arrow-right" href="/pydantic/your-first-model">
  Learn how to create a Pydantic BaseModel subclass, define fields, and instantiate validated data objects.
</Card>
