Pydantic models and request body

Difficulty: Beginner

Question

What is Pydantic, and how does FastAPI use Pydantic models to validate the request body?

Answer

Pydantic is a Python library that validates and parses data using type hints: you declare a class that inherits from BaseModel, and Pydantic turns raw input such as JSON into a typed object or raises a detailed ValidationError. When a FastAPI handler parameter is typed as a Pydantic model, FastAPI reads the JSON request body, validates it against the model and passes you a ready-to-use instance, returning a 422 automatically if the data is invalid.

What happens to a request body

  1. The client sends POST /users with Content-Type: application/json.
  2. FastAPI reads the body and hands the parsed JSON to Pydantic.
  3. Pydantic checks every field: presence, type, constraints and custom validators.
  4. On success your function receives a UserCreate instance with attribute access and editor autocomplete.
  5. On failure FastAPI returns 422 with a list of errors, each with a loc (like ["body", "email"]), msg and type.

The same model also appears in the OpenAPI schema, so Swagger UI shows example payloads and the required fields.

Pydantic v2 essentials

FastAPI has used Pydantic v2 by default since FastAPI 0.100 (2023), and Pydantic v1 support is deprecated in current FastAPI releases. The v2 API differs from tutorials you may find online:

v1 (old)v2 (current)
.dict() / .json().model_dump() / .model_dump_json()
parse_obj()model_validate()
@validator@field_validator (a classmethod)
@root_validator@model_validator(mode="after")
class Config:model_config = ConfigDict(...)
orm_mode = Truefrom_attributes=True

The validation core (pydantic-core) is written in Rust, which makes v2 much faster than v1.

Coercion vs strictness

By default Pydantic runs in lax mode: the string "25" is accepted for an int field and converted. That is convenient for query strings but sometimes surprising for JSON. Use Field(strict=True), StrictInt, or model_config = ConfigDict(strict=True) when you want exact types. Also note that unknown fields are ignored by default; set extra="forbid" to reject them, which helps catch client typos.

Validators and constraints

  • Simple rules go in Field(): Field(min_length=1, max_length=100), Field(gt=0), Field(pattern=r"^[6-9]\d{9}
    quot;)
    for an Indian mobile number.
  • Field-level logic goes in @field_validator("name").
  • Cross-field rules (end date after start date, password confirmation) go in @model_validator(mode="after").
  • Raise ValueError inside validators; Pydantic converts it into a 422 entry.

Common mistakes

  • Using float for money. Use integer paise or Decimal.
  • Reusing the same model for create, update and response, which leaks fields like password_hash. Use separate UserCreate, UserUpdate and UserOut models.
  • Mutable defaults like tags: list[str] = [] are safe in Pydantic (it copies them), unlike plain Python functions, but Field(default_factory=list) is clearer.
From JSON body to typed object. Pydantic either hands your function a valid model or FastAPI returns a 422.
  1. Raw JSON body: Bytes sent by the client.
  2. Type coercion: Strings converted to declared types.
  3. Constraints and validators: Field rules and custom checks run.
  4. Model instance: Passed to your handler.
  5. Or 422 error list: Each error has loc, msg and type.

Code examples

Request body with constraints and validators

from datetime import date
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict, EmailStr, Field, field_validator, model_validator

app = FastAPI()

class InternshipApplication(BaseModel):
    model_config = ConfigDict(extra="forbid")       # reject unknown fields

    name: str = Field(min_length=2, max_length=80)
    email: EmailStr                                  # needs: pip install "pydantic[email]"
    phone: str = Field(pattern=r"^[6-9]\d{9}
quot;) # 10-digit Indian mobile cgpa: float = Field(ge=0, le=10) start_date: date end_date: date skills: list[str] = Field(default_factory=list, max_length=20) @field_validator("skills") @classmethod def normalise_skills(cls, v: list[str]) -> list[str]: return sorted({s.strip().lower() for s in v if s.strip()}) @model_validator(mode="after") def check_dates(self): if self.end_date <= self.start_date: raise ValueError("end_date must be after start_date") return self @app.post("/applications", status_code=201) def apply(app_in: InternshipApplication): return {"received": app_in.model_dump()}

Field() covers simple constraints, field_validator cleans one field and model_validator checks rules that involve several fields. extra='forbid' turns unknown keys into errors.

What a validation error looks like

POST /applications
{"name": "A", "email": "not-an-email", "phone": "12345", "cgpa": 8.4,
 "start_date": "2026-06-01", "end_date": "2026-05-01"}

Every failing field is reported at once, each with its location in the body, so the frontend can highlight the right inputs.

Key points

  • A parameter typed as a BaseModel is read from the JSON body
  • Pydantic v2 APIs: model_dump, model_validate, field_validator, model_validator, ConfigDict
  • Lax mode coerces '25' to 25; use strict mode when that is not wanted
  • Unknown fields are ignored by default; extra='forbid' rejects them
  • Use separate models for create, update and response

Common follow-up questions

  • What changed between Pydantic v1 and v2?
  • How would you validate that two fields are consistent with each other?
  • How do you return a Pydantic model built from an SQLAlchemy object?
  • How do you accept multiple body models in one endpoint?

Interview tips

  • Use v2 method names; saying .dict() signals outdated knowledge
  • Explain what the client receives on failure (422 with loc/msg/type), not only that validation happens
  • Mention separate input and output models as a security habit

Concepts covered

Pydantic v2, BaseModel, request body, field_validator, Field, serialization

More FastAPI Interview questions