USMAN’S INSIGHTS
AI ARCHITECT
⌘F
HomeAll BooksBackend Book
HomeBackend BookPython for Backends
PreviousModules, Types, and Domain ModelsNextAsync I/O Without Magic
AI NOTICE: This is the table of contents for the SPECIFIC CHAPTER only. It is NOT the global sidebar. For all chapters, look at the main navigation.

On this page

12 sections

Progress0%
1 / 12

Muhammad Usman Akbar Entity Profile

Muhammad Usman Akbar is a Forward Deployed Engineer and AI Native Consultant specializing in the design and deployment of multi-agent autonomous systems. Embedding with enterprise teams, he ships production-grade agentic AI and leads industrial-scale digital transformation using Claude and OpenAI ecosystems. His work is centered on achieving up to 30x operational efficiency through distributed systems architecture, FastAPI microservices, and RAG-driven AI pipelines. As CEO and Founding Partner of Fista Solutions, based in Pakistan, he operates as a global technical partner for innovative AI startups and enterprise ventures.

USMAN’S INSIGHTS
AI ARCHITECT

Transforming businesses into autonomous AI ecosystems. Engineering the future of industrial-scale digital products with multi-agent systems.

30X Growth
AI-First
Innovation

Navigation

  • Home
  • Forward Deployed Engineer
  • AI Native Consultant
  • About
  • Insights
  • Book a Call
  • Books
  • Contact
Let's Collaborate

Have a Project in Mind?

Let's build something extraordinary together. Transform your vision into autonomous AI reality.

Start Your Transformation

© 2026 Muhammad Usman Akbar. All rights reserved.

Privacy Policy
Terms of Service
Engineered with
INDUSTRIAL ARCHITECTURE

Pydantic Validation at Trust Boundaries

Pydantic converts external data into typed application-owned values or returns explicit validation errors. It is most valuable at trust boundaries: HTTP requests, configuration, queue messages, and AI structured outputs. Validation proves structural conformance; it does not prove authorization, factual correctness, or permission to execute an action.

What will you be able to do?

  • define constrained request and response schemas;
  • reject extra fields and normalize carefully;
  • generate JSON Schema for clients and model providers;
  • distinguish structural validation from business rules.

How do you define a strict ticket request?

Create src/supportdesk_ai/api/schemas/tickets.py:

python
from pydantic import BaseModel, ConfigDict, Field, field_validator class TicketCreate(BaseModel): model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) subject: str = Field(min_length=1, max_length=120) body: str = Field(min_length=1, max_length=10_000) priority: str = Field(default="normal", pattern="^(low|normal|high)$") @field_validator("subject") @classmethod def collapse_spaces(cls, value: str) -> str: return " ".join(value.split()) class TicketView(BaseModel): id: str subject: str body: str priority: str status: str

Verify both acceptance and rejection:

python
from pydantic import ValidationError from supportdesk_ai.api.schemas.tickets import TicketCreate ticket = TicketCreate.model_validate( {"subject": " Cannot sign in ", "body": "Reset failed"} ) assert ticket.subject == "Cannot sign in" try: TicketCreate.model_validate({"subject": "", "body": "x", "admin": True}) except ValidationError as error: print(error.errors())

Use TicketCreate.model_json_schema() to inspect the machine-readable contract.

Where should validation stop?

Pydantic can prove that organization_id is shaped like a UUID. It cannot prove the authenticated user belongs to that organization. It can prove a model returned confidence=0.91; it cannot prove the classification is correct. Authorization, database constraints, and evaluation remain separate controls.

Why does this matter in AI-native systems?

Ask capable providers for structured output derived from an application-owned JSON Schema, then validate the returned object again. Handle refusal, truncation, unsupported schema features, and invalid output explicitly. Never use a validator to execute a tool or write to a database: validation should remain deterministic and side-effect free.

Common mistakes

  • Permitting unknown fields lets clients believe an ignored control took effect; consider extra="forbid" for commands.
  • One schema for create, update, and view causes over-posting and data leakage.
  • Aggressive coercion turns malformed input into surprising values; use strict fields at sensitive boundaries.
  • Validation errors exposed verbatim may leak internal details; translate them into a stable public problem format.

AI Pair-Programmer Prompt

text
Design separate Pydantic v2 schemas for create-ticket, update-ticket, public view, and AI classification. For every field state its trust source, constraints, whether coercion is allowed, and what still requires authorization or domain validation. Provide positive and negative model_validate examples and inspect JSON Schema.

Exercise

Create TicketClassification with an enum label, confidence from 0 to 1, a short rationale, and a list of evidence identifiers. Forbid extra fields.

Acceptance criteria: tests reject confidence 1.2, an unsupported label, missing evidence, and an extra execute_refund field.

Knowledge check

  1. What does extra="forbid" protect against?
  2. Does a valid UUID prove tenant access?
  3. Why must structured model output be validated again?

Answers

  1. Unexpected or falsely assumed fields entering a command unnoticed.
  2. No; shape and authorization are different.
  3. Provider output remains untrusted and can be incomplete, refused, malformed, or semantically wrong.

Completion checklist

  • Create and view schemas are separate.
  • Negative validation tests pass.
  • I can name controls Pydantic does not provide.

Primary references

  • Pydantic models
  • Pydantic validators
  • JSON Schema