What Is Pydantic?
Understand why raw JSON needs validation before your code can trust it
The problem with raw JSON
When a client sends JSON to your API, Python receives it as a plain dictionary. Nothing enforces the data types. A request like this is perfectly valid JSON:
{"description": "Coffee", "amount": "three dollars"}Your code expects amount to be a number. But Python will not raise an error — it will store the string "three dollars" and break later when you try to do math with it. The bug surfaces far from the cause, making it hard to trace.
Missing fields cause the same problem. If a client sends {"description": "Coffee"} with no amount, your code fails with a KeyError at the point where it reads the value.
How Pydantic fixes this
Pydantic lets you define a model class that describes the exact shape of your data. Each field has a name and a type. When data arrives, Pydantic checks every field against the model before your code runs.
from pydantic import BaseModel
class Expense(BaseModel):
description: str
amount: float
category: strIf a client sends "three dollars" for amount, Pydantic rejects the request immediately with a clear error message. Your endpoint code never executes with bad data.
FastAPI uses Pydantic models automatically. You define the model, use it as a type hint in your endpoint, and FastAPI validates every incoming request against it.
What you will build next
In the next chapter, you will create an Expense model with field-level constraints. The model will reject negative amounts, empty descriptions, and invalid categories — all before your endpoint logic runs.