Generic Example — Schemas & Validation
This page shows the schema layer (Pydantic models) for a typical entity. For the full end-to-end pattern, see:
What belongs in schemas.py
- Request/response schemas (
Create,Update,Response) - Field constraints (
max_length, numeric bounds) - Validation of all user-provided strings (length + format); sanitize only fields that intentionally accept HTML (rich text)
Example schemas.py
from __future__ import annotations
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, ConfigDict, Field, field_validator
class ItemCreate(BaseModel):
name: str = Field(..., max_length=100)
description: Optional[str] = Field(None, max_length=500)
price_cents: int = Field(..., ge=1, le=10_000_000)
class ItemUpdate(BaseModel):
name: Optional[str] = Field(None, max_length=100)
description: Optional[str] = Field(None, max_length=500)
price_cents: Optional[int] = Field(None, ge=1, le=10_000_000)
class ItemResponse(BaseModel):
id: str
tenant_id: str
name: str
description: Optional[str]
price_cents: int
created_at: datetime
updated_at: datetime
model_config = ConfigDict(from_attributes=True)
Notes
- Always include max length constraints on string fields.
- Only sanitize fields that are intended to store/render HTML (rich text); keep sanitization centralized and consistent (don’t hand-roll per-module cleaners).