← Home ← Codex ← DEBT
Browse by Category
+ added · updated 7d
← Back to glossary

Pydantic

Python Python 3.8+ Intermediate
debt(d7/e5/b5/t5)
d7 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'only careful code review or runtime testing' (d7). Missing Pydantic validation at API boundaries isn't flagged by mypy/ruff — they check static types, not whether runtime validation exists. Manual isinstance() checks pass linting fine; the absence of Pydantic shows up only in code review or when malformed input hits production.

e5 Effort Remediation debt — work required to fix once spotted

Closest to 'touches multiple files / significant refactor in one component' (e5). Per quick_fix, introducing Pydantic means defining BaseModel classes and replacing manual validation across API handlers — not a one-liner. Migrating V1→V2 patterns (@validator → @field_validator, dict() → model_dump()) compounds the effort within the component.

b5 Burden Structural debt — long-term weight of choosing wrong

Closest to 'persistent productivity tax' (b5). Pydantic applies across web and CLI contexts (per applies_to) and becomes load-bearing at every data boundary; every new endpoint or settings module is shaped by model definitions. Not architectural (b7+) since it's swappable per-module, but a persistent presence.

t5 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'notable trap most devs eventually learn' (t5). Per misconception, devs think Pydantic is FastAPI-only. Per common_mistakes, the default coercion ('42' → 42 without strict=True) and post-construction mutation bypassing validators are documented gotchas that contradict the 'validation always protects me' intuition.

About DEBT scoring →

Also Known As

Pydantic V2 BaseModel data validation

TL;DR

A Python library for data validation using type annotations — defining models as classes with typed fields that validate and coerce input data at runtime.

Explanation

Pydantic V2 (Rust-powered) validates data against type-annotated models. Fields support validators, default values, aliases, and computed properties. BaseModel parses and validates on instantiation — invalid data raises ValidationError with detailed field-level errors. Pydantic is the foundation of FastAPI and is widely used for settings management (BaseSettings), API request/response models, and data pipeline validation.

Common Misconception

Pydantic is only for FastAPI — it is a standalone validation library useful anywhere you need type-safe data parsing: CLI tools, ETL pipelines, settings management.

Why It Matters

Pydantic replaces dozens of manual isinstance() checks with a declarative model definition — invalid data raises a descriptive ValidationError with field paths instead of cryptic AttributeError later.

Common Mistakes

  • Using Pydantic V1 patterns in V2 — @validator is replaced by @field_validator, class Config by model_config.
  • Not using model.model_dump() (V2) vs dict() (V1) — API has changed between versions.
  • Expecting Pydantic to validate output, not just input — validation happens at parse time; mutating fields after construction bypasses validators.
  • Not using model_config = ConfigDict(strict=True) when coercion should be forbidden — Pydantic coerces '42' to int by default.

Code Examples

✗ Vulnerable
# Manual validation — verbose and easy to miss:
def create_user(data: dict) -> dict:
    if not isinstance(data.get('email'), str) or '@' not in data['email']:
        raise ValueError('Invalid email')
    if not isinstance(data.get('age'), int) or data['age'] < 0:
        raise ValueError('Invalid age')
    return {'email': data['email'], 'age': data['age']}
✓ Fixed
from pydantic import BaseModel, EmailStr, Field

class CreateUserRequest(BaseModel):
    email: EmailStr
    age: int = Field(ge=0, le=150)
    name: str = Field(min_length=1, max_length=100)

# Usage:
try:
    user = CreateUserRequest(**request_data)  # Validates and coerces
except ValidationError as e:
    print(e.errors())  # Detailed field-level errors

Added 15 Mar 2026
Edited 22 Mar 2026
Views 41
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 1 ping S 1 ping S 2 pings M 1 ping T 1 ping W 0 pings T 0 pings F 0 pings S 0 pings S 1 ping M 0 pings T 1 ping W 0 pings T 0 pings F 0 pings S 1 ping S 0 pings M 0 pings T 0 pings W
No pings yet today
No pings yesterday
Amazonbot 7 Perplexity 5 Ahrefs 4 Unknown AI 4 Google 4 Bing 3 Scrapy 3 ChatGPT 1 Claude 1 Sogou 1 PetalBot 1
crawler 31 crawler_json 2 pre-tracking 1
DEV INTEL Tools & Severity
🟡 Medium ⚙ Fix effort: Medium
⚡ Quick Fix
Use Pydantic v2 for data validation at API boundaries — it validates and coerces types at runtime using Python type annotations, the equivalent of PHP's constructor-validated value objects
📦 Applies To
python 3.8 web cli
🔗 Prerequisites
🔍 Detection Hints
Manual isinstance() validation in API handler; dict access without validation; no runtime type checking at API boundaries
Auto-detectable: ✓ Yes mypy pylint ruff
⚠ Related Problems
🤖 AI Agent
Confidence: Medium False Positives: Low ✗ Manual fix Fix: Medium Context: File Tests: Update


✓ schema.org compliant