Some text some message..
Back 🧠 Pydantic Model in Python — Explained in Detail 27 Jul, 2025

🔷 What is Pydantic?

Pydantic is a powerful data validation and settings management library used in Python. It uses Python type annotations to validate and serialize data easily. Pydantic models are built using Python classes, making it intuitive and easy to maintain.

Core Feature: Data parsing & validation using Python's standard type hints.

📦 Commonly used with frameworks like FastAPI, Typer, or in data pipelines for schema enforcement.


📌 Key Features of Pydantic

Feature Description
Type enforcement Ensures the data matches the expected type (e.g., int, str, datetime)
Automatic data conversion Converts data types when possible (e.g., string to int)
Validation Raises clear, informative errors if data is invalid
Nested models Supports complex, nested data structures
Export and serialization .dict(), .json() methods to convert models easily
Environment settings management  Helpful for configs via BaseSettings

🧰 How to Install Pydantic

pip install pydantic

📘 Example: Basic Pydantic Model

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    email: str
    is_active: bool = True

# ✅ Valid data
user = User(id=1, name="Alice", email="alice@example.com")
print(user)

# ❌ Invalid data (raises ValidationError)
invalid_user = User(id="abc", name="Bob", email="bob@example.com")

Automatically converts or rejects data based on type.


🔁 Built-in Validation & Conversion

from pydantic import BaseModel

class Product(BaseModel):
    id: int
    price: float
    available: bool

product = Product(id="1", price="99.99", available="true")
print(product)

🎯 Output:

id=1 price=99.99 available=True

🏗️ Nested Models

from typing import List
from pydantic import BaseModel

class Address(BaseModel):
    city: str
    zipcode: str

class Person(BaseModel):
    name: str
    age: int
    address: Address
    hobbies: List[str]

data = {
    "name": "John",
    "age": 30,
    "address": {
        "city": "New York",
        "zipcode": "10001"
    },
    "hobbies": ["reading", "coding"]
}

person = Person(**data)
print(person.address.city)

🧪 Validators (Custom Validation)

from pydantic import BaseModel, validator

class User(BaseModel):
    username: str
    password: str

    @validator('password')
    def password_strength(cls, v):
        if len(v) < 6:
            raise ValueError('Password too short!')
        return v

User(username="admin", password="123456")  # Valid
User(username="admin", password="123")     # Error

🧾 Use Cases of Pydantic

Use Case Explanation
✅ FastAPI Backend Validate request/response models
📊 Data Ingestion Pipelines Schema validation in ETL/ELT processes
📄 Configuration Handling Use BaseSettings for environment-based app configuration
💬 JSON Parsing Convert and validate incoming JSON files
🧪 Unit Testing Mocking and validating test data
📁 File and API Data Models Ensures integrity of external data before processing

⚙️ BaseSettings for App Configs

from pydantic import BaseSettings

class Settings(BaseSettings):
    database_url: str
    secret_key: str

    class Config:
        env_file = ".env"

settings = Settings()
print(settings.database_url)

🌐 Serialization: .dict() and .json()

user = User(id=1, name="Alice", email="alice@example.com")
print(user.dict())
print(user.json())

📌 Summary

Concept Description
BaseModel Core class to define schema with type annotations
validator Add custom field validation logic
.dict() Convert model to Python dictionary
.json() Convert model to JSON string
BaseSettings Manage app settings using env variables

🎨 Infographic (Text Style)

+------------------------+
|      PYDANTIC          |
+------------------------+
| ✅ Type-safe classes   |
| 🔁 Auto-conversion     |
| 🔒 Field validation    |
| 🏗️  Nested models       |
| 📦 JSON support        |
| 🔧 App config loading  |
+------------------------+