← Back to FastAPI, page 1

fastapi-0009 · Easy fresher

How do you add validation rules to Pydantic v2 model fields used in FastAPI?

Use Field() with constraints such as min_length, max_length, pattern, gt, ge, lt, le, multiple_of and max_digits, or Annotated types that bundle constraints for reuse. Pydantic types like EmailStr (with the email-validator package), HttpUrl, PositiveInt and constr-style Annotated types cover common cases. Invalid input yields a 422 response listing each failing field.

Full answer

Type hints check the type; Field() adds rules about the value.

python
class Student(BaseModel):
    name: str = Field(min_length=2, max_length=50)
    roll_no: str = Field(pattern=r"^[A-Z]{2,4}-\d{2,4}$")
    age: int = Field(ge=5, le=25)
    fee: Decimal = Field(gt=0, max_digits=8, decimal_places=2)
    attendance: float = Field(ge=0, le=100)

Common constraints:

  • Strings: min_length, max_length, pattern (v2 renamed regex to pattern).
  • Numbers: gt, ge, lt, le, multiple_of; decimals: max_digits, decimal_places.
  • Lists: min_length, max_length (v1 used min_items/max_items).
  • default, default_factory (for lists and dicts), alias (JSON name differs from the attribute), description and examples for docs.

Reusable constrained types with Annotated:

python
RollNo = Annotated[str, Field(pattern=r"^[A-Z]{2,4}-\d{2,4}$")]
Percent = Annotated[float, Field(ge=0, le=100)]

Built-in special types: EmailStr (install email-validator), HttpUrl, PositiveInt, conint-style helpers (prefer Annotated in v2), UUID4, PastDate, FutureDate, SecretStr (hides the value in logs and repr).

Strict vs lax: by default Pydantic converts compatible input ("16" to 16). Field(strict=True) or ConfigDict(strict=True) accepts only the exact type, useful where silent conversion would hide client bugs.

String cleanup: ConfigDict(str_strip_whitespace=True) trims spaces before validation.

When rules need logic (cross-field checks, lookups), use field_validator or model_validator.

python
from decimal import Decimal
from typing import Annotated

from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict, Field

RollNo = Annotated[str, Field(pattern=r"^[A-Z]{2,4}-\d{2,4}$")]
Percent = Annotated[float, Field(ge=0, le=100)]


class Student(BaseModel):
    model_config = ConfigDict(str_strip_whitespace=True)

    name: str = Field(min_length=2, max_length=50)
    roll_no: RollNo
    age: int = Field(ge=5, le=25)
    fee: Decimal = Field(gt=0, max_digits=8, decimal_places=2)
    attendance: Percent
    subjects: list[str] = Field(default_factory=list, max_length=6)


app = FastAPI()


@app.post("/students")
def add(student: Student):
    return student


c = TestClient(app)
ok = {"name": "  Rhea  ", "roll_no": "BCA-17", "age": 19, "fee": "15000.50", "attendance": 92.5}
print(c.post("/students", json=ok).json())

bad = {"name": "R", "roll_no": "bca17", "age": 40, "fee": "0", "attendance": 101,
       "subjects": ["a", "b", "c", "d", "e", "f", "g"]}
for err in c.post("/students", json=bad).json()["detail"]:
    print(err["loc"][-1], "->", err["type"])

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'name': 'Rhea', 'roll_no': 'BCA-17', 'age': 19, 'fee': '15000.50', 'attendance': 92.5, 'subjects': []} name -> string_too_short roll_no -> string_pattern_mismatch age -> less_than_equal fee -> greater_than attendance -> less_than_equal subjects -> too_long

Key points

  • Field() adds value constraints to type hints
  • v2 renames: regex -> pattern, min_items -> min_length
  • Annotated aliases make reusable constrained types
  • Special types: EmailStr, HttpUrl, SecretStr, PositiveInt
  • strict=True disables lax conversion

Common mistakes

  • Using v1 names like regex= or min_items= in Pydantic v2
  • Using a mutable default list instead of default_factory=list
  • Writing custom validators for rules Field() already supports
  • Forgetting to install email-validator before using EmailStr

Follow-ups

  • How would you validate that end_date is after start_date?
  • What does strict mode change?
  • How do you reuse the same constraint across ten models?

Tips

  • Name constraints for strings, numbers and lists
  • Show an Annotated reusable type
  • Mention the v1 to v2 renames