← Back to FastAPI, page 4

fastapi-0069 · Medium mid

How do you build reusable validated types in Pydantic v2 with Annotated, AfterValidator and BeforeValidator?

Annotated[base_type, Validator(...)] attaches validation to a type instead of a model, so the same rule is reused across fields and models. AfterValidator runs after Pydantic's own parsing (receives the typed value), BeforeValidator runs before it (receives raw input and can normalise), PlainValidator replaces parsing, and WrapValidator surrounds it. Raise ValueError or AssertionError to report failure.

Full answer

Instead of repeating @field_validator in every model, define the rule once:

python
def normalise_roll(v: str) -> str:
    return v.strip().upper()

def check_roll(v: str) -> str:
    if not re.fullmatch(r"[A-Z]{2,4}-\d{1,5}", v):
        raise ValueError("roll number must look like BCA-123")
    return v

RollNo = Annotated[str, BeforeValidator(str.strip), AfterValidator(normalise_roll), AfterValidator(check_roll)]

Then roll_no: RollNo anywhere, including list items (list[RollNo]), query parameters and Annotated[..., Query()] function parameters in FastAPI.

Validator kinds:

  • BeforeValidator(func): runs first with the raw value (could be int, None, a list). Good for coercions like "split comma-separated string into a list" or stripping.
  • AfterValidator(func): runs after the standard validation, so func can rely on the type being correct. Most checks belong here.
  • PlainValidator(func): replaces the built-in parsing (no type check); use rarely.
  • WrapValidator(func): receives (value, handler), can call handler(value) inside try/except or skip it.

Order: validators in an Annotated run in a defined order: Before and Wrap validators from right to left, After validators left to right (check the documentation for the exact order when mixing). Test the combination.

Errors: raising ValueError produces a value_error entry in the 422 body with the message; PydanticCustomError("code", "message {x}", {"x": 1}) gives custom type codes. AssertionError also works, although asserts disappear under python -O, so prefer ValueError.

Compared with field_validator: the Annotated form travels with the type (shared rules), while field_validator lives in the model (model-specific rules or rules needing other fields via info.data). Combine both. Reusable types also keep OpenAPI constraints if you use Field(pattern=...) inside the Annotated metadata, which a function validator cannot express.

python
import re
from typing import Annotated

from fastapi import FastAPI, Query
from fastapi.testclient import TestClient
from pydantic import AfterValidator, BaseModel, BeforeValidator, ValidationError


def check_roll(v: str) -> str:
    if not re.fullmatch(r"[A-Z]{2,4}-\d{1,5}", v):
        raise ValueError("roll number must look like BCA-123")
    return v


def split_csv(v):
    return [p.strip() for p in v.split(",") if p.strip()] if isinstance(v, str) else v


RollNo = Annotated[str, BeforeValidator(str.strip), AfterValidator(str.upper), AfterValidator(check_roll)]
RollNos = Annotated[list[RollNo], BeforeValidator(split_csv)]


class Enrolment(BaseModel):
    roll_no: RollNo
    friends: RollNos = []


print(Enrolment(roll_no="  bca-17 "))
print(Enrolment(roll_no="BCA-1", friends="ca-2, ca-3"))
try:
    Enrolment(roll_no="17-BCA")
except ValidationError as exc:
    print([(e["loc"], e["type"], e["msg"]) for e in exc.errors()])

app = FastAPI()


@app.get("/lookup")
def lookup(roll_no: Annotated[RollNo, Query()], others: Annotated[RollNos, Query()] = []):
    return {"roll_no": roll_no, "others": others}


c = TestClient(app)
print(c.get("/lookup", params={"roll_no": " bca-9"}).json())
print(c.get("/lookup", params={"roll_no": "bad"}).json()["detail"][0]["msg"])

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): roll_no='BCA-17' friends=[] roll_no='BCA-1' friends=['CA-2', 'CA-3'] [(('roll_no',), 'value_error', 'Value error, roll number must look like BCA-123')] {'roll_no': 'BCA-9', 'others': []} Value error, roll number must look like BCA-123

Key points

  • Annotated types attach validation to a type for reuse
  • Before runs on raw input; After on the typed value
  • Raise ValueError (not assert) to fail
  • Works for list items, models and FastAPI parameters
  • Use Field constraints in Annotated when you want them in OpenAPI

Common mistakes

  • Repeating the same field_validator in many models
  • Using assert for validation
  • Putting checks that assume a type in a Before validator
  • Expecting a function validator to add constraints to the OpenAPI schema

Follow-ups

  • What is the order of multiple validators in Annotated?
  • How do you raise a custom error type?
  • When would you use WrapValidator?

Tips

  • Contrast Before and After
  • Show a reusable type used in several places
  • Mention OpenAPI limitation