📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials FastAPI Request Body and Pydantic

Request Body and Pydantic

5 min read Quiz at the end
Define Pydantic request bodies with field validators, model validators, and EmailStr.

Request Body with Pydantic

from pydantic import BaseModel, EmailStr, field_validator, model_validator
from typing import Optional
import re

class UserCreate(BaseModel):
    name:     str
    email:    EmailStr
    password: str
    age:      Optional[int] = None

    @field_validator("name")
    @classmethod
    def name_must_be_valid(cls, v: str) -> str:
        if len(v.strip()) < 2:
            raise ValueError("Name must be at least 2 characters")
        return v.strip()

    @field_validator("password")
    @classmethod
    def password_strength(cls, v: str) -> str:
        if not re.search(r"[A-Z]", v):
            raise ValueError("Password must contain uppercase letter")
        if len(v) < 8:
            raise ValueError("Password must be at least 8 characters")
        return v

    @model_validator(mode="after")
    def check_age(self) -> "UserCreate":
        if self.age and self.age < 18:
            raise ValueError("Must be 18 or older")
        return self
Topic Quiz · 2 questions

Test your understanding before moving on

1. What does @field_validator("name") do?
💡 @field_validator decorates a classmethod that validates and can transform the value.
2. What happens when Pydantic validation fails in FastAPI?
💡 FastAPI returns 422 with field-level error details when Pydantic validation fails.