This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: fastapi-pydantic-v2-serialization-boundary-invariant

FastAPI Pydantic v2 Compiled Boundary Serialization and ORM Leak Prevention

Enforces compiled C/Rust-level serialization boundaries via Pydantic v2's pydantic-core rather than raw Python dictionary hydration or unvalidated ORM pass-through. Mandates explicit `response_model` definitions with `from_attributes=True` and strict field exclusion to eliminate arbitrary internal ORM attribute leaks (e.g., hashed passwords, internal foreign keys) while reducing CPU overhead and latency. Prohibits manual `.dict()` or unvalidated `dict(orm_instance)` dumps across public HTTP egress boundaries.

Prohibited Anti-Pattern: Leaking sensitive ORM attributes and degrading serialization throughput via ad-hoc dictionary conversions or unconstrained model returns

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI Pydantic v2 Compiled Boundary Serialization and ORM Leak Prevention - Enforces compiled C/Rust-level serialization boundaries via Pydantic v2's pydantic-core rather than raw Python dictionary hydration or unvalidated ORM pass-through. Mandates explicit `response_model` definitions with `from_attributes=True` and strict field exclusion to eliminate arbitrary internal ORM attribute leaks (e.g., hashed passwords, internal foreign keys) while reducing CPU overhead and latency. Prohibits manual `.dict()` or unvalidated `dict(orm_instance)` dumps across public HTTP egress boundaries.
globs: app/**/*.py, src/**/*.py, api/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-pydantic-v2-serialization-boundary-invariant"
---

# FastAPI Pydantic v2 Compiled Boundary Serialization and ORM Leak Prevention

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Leaking sensitive ORM attributes and degrading serialization throughput via ad-hoc dictionary conversions or unconstrained model returns

## System Constraints
You are a Principal Backend Architect enforcing strict Pydantic v2 serialization boundary invariants within FastAPI applications. Mandate explicit response models, rust-accelerated validation via `from_attributes=True`, and zero unvalidated dictionary egress to prevent secret leakage and latency degradation.

## Strict Guidelines
- Engineers MUST ALWAYS declare an explicit `response_model` on FastAPI route decorators or return a typed `TypeAdapter(Model).dump_json()` payload to invoke `pydantic-core` validation.
- Engineers MUST configure `model_config = ConfigDict(from_attributes=True, extra='forbid')` on response schemas mapping from SQLAlchemy/SQLModel instances instead of using legacy `orm_mode = True`.
- Engineers MUST NOT convert ORM entities to raw Python dictionaries via `vars()`, `__dict__`, or custom dictionary comprehensions before serialization.
- Services MUST NEVER return raw database models directly from endpoint functions without a confining Pydantic v2 schema projection.
- Schemas MUST explicitly define field allowlists; sensitive attributes such as `hashed_password`, `totp_secret`, or internal trace identifiers MUST NOT exist on egress contracts even as optional fields.

## Bad vs Good Implementations
### Pydantic v2 ORM Egress Boundary: Uncontrolled Raw Model vs. Compiled Schema Projection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accessing `user.__dict__` bypasses Pydantic's compiled rust-core validation, exposes internal SQLAlchemy state (`_sa_instance_state`), leaks sensitive fields like `hashed_password`, and breaks the OpenAPI contract definition.
```python
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.db.models import User
from app.db.session import get_db

router = APIRouter()

# Anti-pattern: Returning ORM instance directly without response_model,
# or relying on manual __dict__ serialization which leaks hashed_password
@router.get("/users/{user_id}")
def get_user(user_id: int, db: Session = Depends(get_db)):
    user = db.query(User).filter(User.id == user_id).first()
    # Exposes private ORM attributes, __state__, and hashed_password
    # Incurs Python runtime reflection penalty
    return user.__dict__
```

#### Production Standard (Correct)
> **Standard**: FastAPI applies `response_model=UserRead` via `pydantic-core` C/Rust extraction. Fields are strictly isolated to `id`, `email`, and `is_active`, preventing sensitive attribute leaks and maximizing throughput.
```python
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, ConfigDict, EmailStr
from sqlalchemy.orm import Session
from app.db.models import User
from app.db.session import get_db

router = APIRouter()

class UserRead(BaseModel):
    model_config = ConfigDict(from_attributes=True, extra="forbid")

    id: int
    email: EmailStr
    is_active: bool

@router.get(
    "/users/{user_id}",
    response_model=UserRead,
    status_code=status.HTTP_200_OK
)
def get_user(user_id: int, db: Session = Depends(get_db)) -> User:
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found"
        )
    # FastAPI leverages pydantic-core to validate and extract ONLY declared fields from the ORM object
    return user
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: FastAPI Pydantic v2 Compiled Boundary Serialization and ORM Leak Prevention

FastAPI Pydantic v2 Compiled Boundary Serialization and ORM Leak Prevention defines an industrial-grade behavioral standard for backend engineering. Enforces compiled C/Rust-level serialization boundaries via Pydantic v2's pydantic-core rather than raw Python dictionary hydration or unvalidated ORM pass-through. Mandates explicit `response_model` definitions with `from_attributes=True` and strict field exclusion to eliminate arbitrary internal ORM attribute leaks (e.g., hashed passwords, internal foreign keys) while reducing CPU overhead and latency. Prohibits manual `.dict()` or unvalidated `dict(orm_instance)` dumps across public HTTP egress boundaries. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Leaking sensitive ORM attributes and degrading serialization throughput via ad-hoc dictionary conversions or unconstrained model returns Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftLeaking sensitive ORM attributes and degrading serialization throughput via ad-hoc dictionary conversions or unconstrained model returnsCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS declare an explicit `response_model` on FastAPI route decorators or return a typed `TypeAdapter(Model).dump_json()` payload to invoke `pydantic-core` validation.

Engineers MUST ALWAYS declare an explicit `response_model` on FastAPI route decorators or return a typed `TypeAdapter(Model).dump_json()` payload to invoke `pydantic-core` validation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST configure `model_config = ConfigDict(from_attributes=True, extra='forbid')` on response schemas mapping from SQLAlchemy/SQLModel instances instead of using legacy `orm_mode = True`.

Engineers MUST configure `model_config = ConfigDict(from_attributes=True, extra='forbid')` on response schemas mapping from SQLAlchemy/SQLModel instances instead of using legacy `orm_mode = True`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST NOT convert ORM entities to raw Python dictionaries via `vars()`, `__dict__`, or custom dictionary comprehensions before serialization.

Engineers MUST NOT convert ORM entities to raw Python dictionaries via `vars()`, `__dict__`, or custom dictionary comprehensions before serialization.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST NEVER return raw database models directly from endpoint functions without a confining Pydantic v2 schema projection.

Services MUST NEVER return raw database models directly from endpoint functions without a confining Pydantic v2 schema projection.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Schemas MUST explicitly define field allowlists

Schemas MUST explicitly define field allowlists; sensitive attributes such as `hashed_password`, `totp_secret`, or internal trace identifiers MUST NOT exist on egress contracts even as optional fields.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is FastAPI Pydantic v2 Compiled Boundary Serialization and ORM Leak Prevention critical for AI coding assistants?

Enforces compiled C/Rust-level serialization boundaries via Pydantic v2's pydantic-core rather than raw Python dictionary hydration or unvalidated ORM pass-through. Mandates explicit `response_model` definitions with `from_attributes=True` and strict field exclusion to eliminate arbitrary internal ORM attribute leaks (e.g., hashed passwords, internal foreign keys) while reducing CPU overhead and latency. Prohibits manual `.dict()` or unvalidated `dict(orm_instance)` dumps across public HTTP egress boundaries. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Leaking sensitive ORM attributes and degrading serialization throughput via ad-hoc dictionary conversions or unconstrained model returns) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

FastAPI