Course contentsShow
← AI Engineering
Lesson 1488 of 1,88636. Security in AI SystemsFree lesson

Schema Validation for Structured Inputs

Apply Pydantic and JSON schema validation to ensure inputs conform to expected formats.

Schema Validation for Structured Inputs

You'll learn how to enforce strict input structure requirements using Pydantic and JSON schema to prevent malformed data from reaching your AI system.

When your AI application accepts structured data—like JSON payloads with user preferences, API requests with specific fields, or configuration objects—you need guarantees that the data matches your expected format. Without validation, malformed inputs can cause crashes, bypass security controls, or inject unexpected behavior into your prompts.

What Schema Validation Does

Think of schema validation as a bouncer at a nightclub who checks IDs before anyone enters. The bouncer doesn't just glance—they verify the ID format, check the photo, confirm the birthdate structure, and ensure nothing looks suspicious. Similarly, schema validators ensure every field exists, has the right type, matches length constraints, and conforms to allowed values.

Using Pydantic for Validation

Pydantic provides Python classes that automatically validate input data:

from pydantic import BaseModel, Field, validator

class UserQuery(BaseModel):
    query_text: str = Field(max_length=500)
    language: str = Field(pattern="^(en|es|fr)$")
    temperature: float = Field(ge=0.0, le=1.0)
    
    @validator('query_text')
    def sanitize_query(cls, v):
        if '<script>' in v.lower():
            raise ValueError("Invalid characters detected")
        return v

This enforces that query_text is a string under 500 characters, language matches specific codes, and temperature stays within bounds—before the data ever reaches your LLM.

JSON Schema Alternative

JSON Schema offers language-agnostic validation that works across different systems and can be enforced at API gateways.

Key Takeaway: Schema validation acts as your first line of defense, rejecting malformed or suspicious structured inputs before they can influence your AI system's behavior, complementing the input sanitization strategies you've already learned.