---
title: "Request Validation for AI Agent APIs: Pydantic Models and Custom Validators"
description: "Build robust request validation for AI agent APIs using Pydantic v2 models, custom field validators, and discriminated unions. Learn how to handle nested agent configurations and return clear validation error responses."
canonical: https://callsphere.ai/blog/request-validation-ai-agent-apis-pydantic-models-validators
category: "Learn Agentic AI"
tags: ["FastAPI", "Pydantic", "Validation", "AI Agents", "API Design"]
author: "CallSphere Team"
published: 2026-03-17T00:00:00.000Z
updated: 2026-05-06T01:02:44.846Z
---

# Request Validation for AI Agent APIs: Pydantic Models and Custom Validators

> Build robust request validation for AI agent APIs using Pydantic v2 models, custom field validators, and discriminated unions. Learn how to handle nested agent configurations and return clear validation error responses.

## Why Validation Is Critical for AI Agent APIs

AI agent APIs accept complex, user-facing input: conversation messages, tool configurations, agent parameters, and file references. Without rigorous validation, malformed inputs produce cryptic LLM errors, prompt injection passes unchecked, and debugging becomes a nightmare. Pydantic v2 in FastAPI gives you type-safe, performant validation that catches problems at the API boundary before they reach your agent logic.

Every field that enters your agent system should be validated for type, length, format, and business rules. This is not just about preventing crashes. It is about making your API self-documenting and giving clients clear feedback when something is wrong.

## Basic Request Models

Start with well-typed models for your core agent interactions:

```mermaid
flowchart LR
    CLIENT(["Client SDK"])
    GW["API Gateway
auth plus rate limit"]
    APP["FastAPI app
handlers and DI"]
    VAL["Pydantic validation"]
    SVC["Service layer
business logic"]
    DB[(Database)]
    QUEUE[(Background queue)]
    OBS[(Tracing)]
    CLIENT --> GW --> APP --> VAL --> SVC
    SVC --> DB
    SVC --> QUEUE
    SVC --> OBS
    SVC --> CLIENT
    style GW fill:#4f46e5,stroke:#4338ca,color:#fff
    style APP fill:#f59e0b,stroke:#d97706,color:#1f2937
    style DB fill:#ede9fe,stroke:#7c3aed,color:#1e1b4b
```

```python
from pydantic import BaseModel, Field
from enum import Enum
from typing import Optional

class AgentRole(str, Enum):
    ASSISTANT = "assistant"
    RESEARCHER = "researcher"
    CODER = "coder"

class Message(BaseModel):
    role: str = Field(
        ...,
        pattern="^(user|assistant|system)$",
        description="Message sender role",
    )
    content: str = Field(
        ...,
        min_length=1,
        max_length=32000,
        description="Message content",
    )

class ChatRequest(BaseModel):
    messages: list[Message] = Field(
        ...,
        min_length=1,
        max_length=100,
        description="Conversation history",
    )
    agent_role: AgentRole = AgentRole.ASSISTANT
    temperature: float = Field(
        default=0.7,
        ge=0.0,
        le=2.0,
        description="Sampling temperature",
    )
    max_tokens: Optional[int] = Field(
        default=None,
        ge=1,
        le=16384,
        description="Maximum response tokens",
    )
    session_id: Optional[str] = Field(
        default=None,
        pattern="^[a-zA-Z0-9-]{1,64}$",
        description="Session identifier",
    )
```

The `Field` constraints handle most validation without any custom code. `min_length`, `max_length`, `ge`, `le`, and `pattern` catch invalid inputs instantly.

## Custom Field Validators

For validation logic that goes beyond simple constraints, use Pydantic v2 field validators:

```python
from pydantic import field_validator, model_validator

class AgentConfigRequest(BaseModel):
    system_prompt: str = Field(..., max_length=10000)
    tools: list[str] = Field(default_factory=list)
    model: str = "gpt-4o"
    stop_sequences: list[str] = Field(
        default_factory=list, max_length=4
    )

    @field_validator("system_prompt")
    @classmethod
    def validate_system_prompt(cls, v: str) -> str:
        forbidden = [
            "ignore previous instructions",
            "disregard all prior",
        ]
        lower_v = v.lower()
        for phrase in forbidden:
            if phrase in lower_v:
                raise ValueError(
                    "System prompt contains forbidden content"
                )
        return v.strip()

    @field_validator("tools")
    @classmethod
    def validate_tools(cls, v: list[str]) -> list[str]:
        allowed = {
            "web_search", "calculator", "code_exec",
            "file_read", "database_query",
        }
        invalid = set(v) - allowed
        if invalid:
            raise ValueError(
                f"Unknown tools: {', '.join(invalid)}. "
                f"Allowed: {', '.join(sorted(allowed))}"
            )
        return v

    @field_validator("model")
    @classmethod
    def validate_model(cls, v: str) -> str:
        allowed_models = {
            "gpt-4o", "gpt-4o-mini",
            "claude-3-5-sonnet", "claude-3-haiku",
        }
        if v not in allowed_models:
            raise ValueError(
                f"Model '{v}' not supported. "
                f"Choose from: {', '.join(sorted(allowed_models))}"
            )
        return v
```

## Cross-Field Validation with model_validator

Some validation rules involve multiple fields. Use `model_validator` to check relationships between fields:

```python
class BatchAgentRequest(BaseModel):
    messages: list[Message]
    parallel: bool = False
    max_concurrent: int = Field(default=5, ge=1, le=20)
    timeout_seconds: int = Field(default=60, ge=5, le=300)

    @model_validator(mode="after")
    def validate_batch_config(self):
        if not self.parallel and self.max_concurrent > 1:
            raise ValueError(
                "max_concurrent > 1 requires parallel=True"
            )
        if len(self.messages) > 50 and self.timeout_seconds  ".join(str(x) for x in error["loc"]),
            "message": error["msg"],
            "type": error["type"],
        })

    return JSONResponse(
        status_code=422,
        content={
            "error": "validation_error",
            "message": "Request validation failed",
            "details": errors,
        },
    )
```

## FAQ

### How do I validate optional fields that should not be empty strings?

Use a field validator that checks for empty strings after stripping whitespace. Pydantic's `min_length=1` on an `Optional[str]` only applies when the value is not `None`. Add a validator like: `@field_validator("field_name") def check(cls, v): if v is not None and not v.strip(): raise ValueError("Cannot be empty"); return v`. This allows `None` but rejects `""` and `"  "`.

### Should I use Pydantic models for response validation too?

Yes. Define `response_model` on your endpoints to ensure responses match a known schema. This catches bugs where your endpoint accidentally returns extra fields, missing fields, or wrong types. It also automatically generates accurate OpenAPI documentation. Use `model_config = ConfigDict(from_attributes=True)` when returning ORM objects directly.

### How do I handle validation for multipart form data with JSON fields?

FastAPI can accept `Form` and `File` parameters alongside Pydantic models. For complex JSON embedded in form data, accept the JSON as a `Form()` string parameter, then parse and validate it manually with your Pydantic model: `config = AgentConfig.model_validate_json(config_json)`. This gives you full Pydantic validation even for form-submitted JSON.

---

#FastAPI #Pydantic #Validation #AIAgents #APIDesign #AgenticAI #LearnAI #AIEngineering

---

Source: https://callsphere.ai/blog/request-validation-ai-agent-apis-pydantic-models-validators
