Python Essentials – Validation with Pydantic
Bank Teller Verification
Imagine you go to a bank to open an account:
You fill out a form with your details (name, age, balance, ID).
The bank teller checks the form:
Is your age a number?
Is your ID valid?
Is the initial deposit non-negative?
If something is wrong → the teller rejects it and asks you to fix it.
If everything is correct → the account is created successfully.
This is exactly what Pydantic does for Python data: it validates incoming data and ensures it is the right type, format, and structure.
🔹 What is Pydantic?
Pydantic is a Python library used for data validation and settings management.
Ensures your data is correct type and format
Automatically parses JSON into Python objects
Raises clear errors if the data is invalid
Perfect for FastAPI APIs and Agentic AI
🔹 Step 1: Install Pydantic
pip install pydantic
🔹 Step 2: Define a Data Model
We define schemas for the data we expect:
from pydantic import BaseModel, Field, ValidationError
class User(BaseModel):
name: str
age: int
balance: float = 0.0
BaseModel→ Base class for all Pydantic modelsField→ optional, can set defaults or constraintsEach attribute has a type
🔹 Step 3: Create & Validate Data
# Valid input
user1 = User(name="Anita", age=25, balance=100.50)
print(user1)
Output:
name='Anita' age=25 balance=100.5
Invalid input:
try:
user2 = User(name="Ravi", age="twenty", balance=-50)
except ValidationError as e:
print(e)
Output:
1 validation error for User
age
value is not a valid integer (type=type_error.integer)
✅ Pydantic automatically catches mistakes
🔹 Step 4: Add Extra Validation
You can enforce rules like “age must be > 0”:
from pydantic import BaseModel, Field, validator
class User(BaseModel):
name: str
age: int = Field(..., gt=0)
balance: float = Field(default=0.0, ge=0.0) # balance >= 0
@validator('name')
def name_must_not_be_empty(cls, v):
if not v.strip():
raise ValueError('Name cannot be empty')
return v
gt=0→ greater than 0ge=0→ greater than or equal to 0@validator→ custom logic
🔹 Step 5: Real-Time Agentic AI Example
Imagine an Agent API that receives a task request:
from pydantic import BaseModel, Field, ValidationError
from fastapi import FastAPI
app = FastAPI()
class TaskRequest(BaseModel):
task_name: str
priority: int = Field(..., ge=1, le=5) # 1 to 5
data_source: str
@app.post("/run_task")
def run_task(task: TaskRequest):
return {"message": f"Running task: {task.task_name} with priority {task.priority}"}
Example Requests:
Valid POST:
{
"task_name": "Fetch AI Articles",
"priority": 3,
"data_source": "Web"
}
✅ Works perfectly
Invalid POST:
{
"task_name": "Fetch AI Articles",
"priority": 10,
"data_source": "Web"
}
❌ Returns:
{
"detail": [
{
"loc": ["body","priority"],
"msg": "ensure this value is less than or equal to 5",
"type": "value_error.number.not_le"
}
]
}
Pydantic automatically validates the request
FastAPI returns a structured error message
Ensures agents never get invalid data
🔹 Step 6: Why Validation Matters in Agentic AI
Ensures agent receives correct inputs
Prevents runtime crashes
Makes APIs secure, predictable, and production-ready
Helps debug quickly if input is wrong
✅ Key Takeaways
ConceptAnalogyPython/Pydantic ExampleValidationBank teller checks formsBaseModel + type hints + validatorDefaults / ConstraintsMinimum deposit / ageField(..., ge=0)Automatic Error ResponseTeller rejects invalid formFastAPI + Pydantic auto error messagesData ParsingForm → structured recordJSON → Python object
Mental Model for Agentic AI:
Agent receives input → must be structured and valid
Pydantic ensures validity → like a bank teller checking forms
Invalid inputs rejected automatically → agent doesn’t crash

