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.

PythonForm Validation

Code

pythonsnippet
21 lines
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: pydantic is 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

FAQ

Does this require external packages?
Yes — `pydantic`. Add it to your project before running the snippet.