In Pydantic, BaseModel is the core class used for data validation and settings management. It provides an easy way to define data models with automatic type validation, serialization, and parsing.
📦 Basic Example
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
email: str
# Valid data
user = User(id=1, name="Abhishek", email="abhi@example.com")
print(user)
# Invalid data: will raise ValidationError
invalid_user = User(id="not_an_int", name=123, email=True)
🔍 Features of BaseModel
Automatic Validation:
Ensures that the data matches the types declared.
Throws ValidationError if data is invalid.
Auto Conversion (when possible):
Will try to coerce types if reasonable.
user = User(id='1', name='Abhi', email='abhi@example.com')
# id is str, but Pydantic will convert to int
3.Dict Support:
Convert model to dictionary easily:
user_dict = user.dict()
4.JSON Support:
user_json = user.json()
5.Field Aliases, Defaults, Optional Fields:
from typing import Optional
class User(BaseModel):
id: int
name: str = "Guest"
email: Optional[str] = None
📌 Real-World Use Cases
FastAPI uses Pydantic models as request and response schemas.
Helps enforce data contracts in APIs.
Useful for configuration management using BaseSettings.
🚫 Error Handling Example
from pydantic import ValidationError
try: user = User(id="not-an-int", name=123, email="wrong") except ValidationError as e: print(e.json())