FastAPI interview question · Most asked

How does FastAPI use Pydantic for request validation?

Summary

Request bodies, query models and settings are declared as Pydantic BaseModel classes. FastAPI parses incoming data into them, validates types and constraints, and returns a 422 response with detailed errors on failure.

Longer Answer

Pydantic v2 (with its Rust core, pydantic-core) coerces compatible input (e.g., '3' → 3 in lax mode), enforces constraints (Field(gt=0, max_length=50)), and supports custom validators (@field_validator, @model_validator). Errors include the location (body.price), message and type, which clients can map to form fields.

Code Example

from pydantic import BaseModel, Field, field_validator, EmailStr

class SignUp(BaseModel):
    email: EmailStr
    password: str = Field(min_length=12)
    age: int = Field(ge=18)

    @field_validator("password")
    @classmethod
    def has_digit(cls, v: str) -> str:
        if not any(c.isdigit() for c in v):
            raise ValueError("password must contain a digit")
        return v

Key Points

  • Models declared with type hints and Field() constraints
  • Invalid input → automatic 422 response
  • @field_validator / @model_validator for custom rules
  • Strict mode disables coercion

More most-asked FastAPI questions

← All FastAPI questions