Pydantic Model for Request Validation
Describe a request payload with a Pydantic model so types and constraints are enforced and clear validation errors are returned automatically.
Code
from typing import Optional
from pydantic import BaseModel, EmailStr, Field, field_validator
class CreateUser(BaseModel):
email: EmailStr
age: int = Field(ge=13, le=120)
nickname: Optional[str] = Field(default=None, max_length=32)
@field_validator("nickname")
@classmethod
def normalize_nickname(cls, value: Optional[str]) -> Optional[str]:
if value is None:
return value
trimmed = value.strip()
return trimmed or None
create_user = CreateUser(email="ada@example.com", age=36, nickname=" ada ")
print(create_user.model_dump())Inside the snippet
One way to read it: the class CreateUser and the function normalize_nickname, doing all the work.
The import line is the dependency contract: Optional, BaseModel, EmailStr, Field, field_validator come from pydantic and nothing else.
What to watch for
- Plan for an install step:
pydanticis a real dependency, resolved by the package manager.
Putting it to use
The primary signature is def normalize_nickname(cls, value: Optional[str]) -> Optional[str]
normalize_nickname is what another module would consume; nothing else here is load-bearing for callers.
Core lines
def normalize_nickname(cls, value: Optional[str]) -> Optional[str]:
if value is None:
return value
trimmed = value.strip()
return trimmed or None
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does this require external packages?
- Yes — `pydantic`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.