How to Validate Forms with Pydantic in Python
Validate Python form and API data with Pydantic v2: strict fields, custom validators, nested models, normalized errors, JSON Schema, and FastAPI integration.
On this page
Introduction
Pydantic turns Python type hints into runtime validation. A model declares the shape of incoming data, and Pydantic rejects values that do not match before the rest of the application sees them. In Pydantic v2 the validation core is written in Rust, configuration moved to ConfigDict, and serialization uses model_dump. The API is concise, but the defaults deserve attention: coercion, extra-field handling, and error formatting all affect whether a form accepts the data you expect.
This tutorial builds a user registration model with email, password, age, nested address data, and cross-field rules. It shows how to normalize validation errors for an API or form, export JSON Schema for documentation, and integrate the model with FastAPI. The examples target Pydantic 2.x and Python 3.10 or newer.
Install Pydantic with email support
EmailStr requires the optional email-validator package:
pip install "pydantic[email]"
Define a model with explicit constraints. Field handles length, numeric bounds, and patterns; StringConstraints keeps reusable string rules readable:
from typing import Annotated
from pydantic import BaseModel, ConfigDict, EmailStr, Field, StringConstraints
Password = Annotated[
str,
StringConstraints(min_length=8, max_length=128, strip_whitespace=False),
]
class Address(BaseModel):
model_config = ConfigDict(extra="forbid")
street: str = Field(min_length=1, max_length=120)
city: str = Field(min_length=1, max_length=80)
postal_code: str = Field(pattern=r"^\d{5}(-\d{4})?$")
class UserForm(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
email: EmailStr
password: Password
age: int = Field(ge=0, le=150)
accept_terms: bool
tags: list[str] = Field(default_factory=list, max_length=10)
address: Address | None = None
extra="forbid" rejects unknown keys instead of silently ignoring them. That catches typos such as emial and prevents a client from smuggling fields that a later **model_dump() call might pass to another layer. str_strip_whitespace=True removes accidental leading and trailing spaces before length checks. Set strip_whitespace=False on password fields if spaces are meaningful; otherwise a trailing space can be silently removed and the user cannot log in with the password they typed.
default_factory=list avoids the classic mutable-default bug. Never write tags: list[str] = []. Pydantic detects some mutable defaults, but default_factory is the correct expression of intent.
Add field and model validators
A field validator handles one value. Decorate it with @field_validator and @classmethod, and return the value:
from pydantic import field_validator, model_validator
class RegistrationForm(UserForm):
@field_validator("password")
@classmethod
def password_strength(cls, value: str) -> str:
if not any(char.isupper() for char in value):
raise ValueError("must include an uppercase letter")
if not any(char.isdigit() for char in value):
raise ValueError("must include a digit")
return value
@model_validator(mode="after")
def terms_must_be_accepted(self):
if not self.accept_terms:
raise ValueError("terms must be accepted")
return self
A mode="after" model validator runs after all fields are validated, so it can compare fields safely. Use it for rules such as “password and confirmation match” or “end date must be after start date”. Do not perform database queries or network calls in a validator. Validation should be deterministic and fast; an availability check belongs in the service layer, where it can return a domain-specific error.
Validators can also normalize values. For example, lower-case an email domain or remove duplicate tags. Keep normalization explicit and idempotent. A validator that silently changes a value the user cannot see makes debugging harder; document it in the field description.
Choose strictness deliberately
Pydantic is lax by default. It accepts "42" for an int field and converts it to 42. That is convenient for HTML forms, where every value arrives as a string, and dangerous for JSON APIs, where a string in a numeric field usually indicates a client bug. Choose per model:
class StrictReading(BaseModel):
model_config = ConfigDict(strict=True)
sensor_id: str
temperature: float
Strict mode rejects coercion, including "1.5" for a float and 1 for a string. It is a better default for machine-to-machine APIs. HTML form handlers may prefer lax mode and convert explicitly at the boundary. Do not mix assumptions within one model; a field that accepts both true and "true" is ambiguous.
ConfigDict(validate_assignment=True) re-validates fields when they are assigned after construction. It is useful for long-lived models that are edited in place, but it adds overhead and can surprise code that expects a plain attribute assignment. model_copy(update=...) does not validate the update by default; call model_validate again if the copy must be trusted.
Normalize errors for users
ValidationError.errors() returns structured entries with a location, error type, message, and input. Strip the documentation URL and map the location to a field name:
from pydantic import ValidationError
def form_errors(exc: ValidationError) -> dict[str, str]:
result: dict[str, str] = {}
for error in exc.errors(include_url=False):
field = ".".join(str(part) for part in error["loc"])
result.setdefault(field, error["msg"])
return result
try:
form = RegistrationForm.model_validate(payload)
except ValidationError as exc:
return {"errors": form_errors(exc)}, 422
setdefault keeps the first error per field. The raw message may mention Python types or internal constraints; for a public API, map error types to product copy instead of returning Pydantic’s text verbatim. Log the raw error with a request id, but do not log the submitted password or other sensitive values.
Pydantic’s error locations are tuples. For a nested address, the location is ("address", "postal_code"). Joining with a dot gives a stable path that a frontend can map to an input. For list items, the location includes an integer index; handle that explicitly if the form renders repeated fields.
Export JSON Schema for documentation
model_json_schema() produces a JSON Schema derived from the same constraints used at runtime. FastAPI uses it to build OpenAPI documentation automatically:
schema = RegistrationForm.model_json_schema()
Because the schema and validation share a source, documentation drift is reduced. Add Field(description=..., examples=[...]) so generated docs explain the expected values. Do not put secrets or real user data in examples. If a field is write-only, exclude it from response models rather than relying on documentation to hide it.
For values that are not a BaseModel, use TypeAdapter:
from pydantic import TypeAdapter
tags = TypeAdapter(list[str]).validate_python(["python", "api"])
TypeAdapter is also useful for parsing a list of models or a union. It avoids wrapping a simple value in a model just to obtain validation.
Integrate with FastAPI
FastAPI accepts a Pydantic model as a request body and returns a 422 response when validation fails. Keep separate input and output models:
class UserOut(BaseModel):
id: int
email: EmailStr
display_name: str
@app.post("/users", response_model=UserOut, status_code=201)
async def create_user(form: RegistrationForm) -> UserOut:
user = await user_service.create(form)
return UserOut(id=user.id, email=user.email, display_name=user.display_name)
Never return the input model directly if it contains a password, even hashed. response_model filters fields, but an explicit output model is easier to audit. Mark sensitive fields with SecretStr so accidental logging prints ********** instead of the value. SecretStr does not encrypt the value; it only prevents casual exposure in repr output.
FastAPI’s 422 body contains the raw error structure. If the frontend needs a stable contract, add an exception handler that converts RequestValidationError into the same {"errors": {field: message}} shape used elsewhere. That keeps browser forms and API clients on one error format.
Test valid and invalid inputs
Use pytest.mark.parametrize to cover boundaries:
import pytest
from pydantic import ValidationError
@pytest.mark.parametrize(
"payload",
[
{"email": "not-an-email", "password": "Password1", "age": 20, "accept_terms": True},
{"email": "[email protected]", "password": "short", "age": 20, "accept_terms": True},
{"email": "[email protected]", "password": "Password1", "age": -1, "accept_terms": True},
{"email": "[email protected]", "password": "Password1", "age": 20, "accept_terms": False},
],
)
def test_rejects_invalid_registration(payload):
with pytest.raises(ValidationError):
RegistrationForm.model_validate(payload)
Add a success case, an extra-field case, and a nested-address error case. Assert on the error location and type rather than the exact English message, which can change between Pydantic releases. For FastAPI, use TestClient and assert the 422 response shape after your exception handler is installed.
Common pitfalls
- Mutable defaults. Use
Field(default_factory=list). - Ignoring extra fields. The default is to ignore them; use
extra="forbid"when typos should fail. - Assuming strict typing. Lax mode coerces strings to numbers.
- Validators with side effects. Keep I/O and authorization out of validators.
- Returning raw error messages. Map them to stable, user-facing copy.
- Returning password fields. Use a separate response model and
SecretStr. - Editing with
model_copy(update=...)and assuming validation. It does not validate by default. - Forgetting
email-validator.EmailStrfails at import or model definition without it.
Conclusion
Pydantic is most effective when the model is treated as the contract at the boundary: explicit constraints, deliberate strictness, validators for deterministic rules, and a stable error format. FastAPI integration is nearly free once the model is correct, but the model does not replace service-level checks such as uniqueness or authorization. Keep those concerns separate, and the same schema can serve forms, APIs, documentation, and tests without duplicating validation logic.
Sources: Pydantic documentation, Pydantic validators, FastAPI request body.
FAQ
- What changed from Pydantic v1 to v2?
- Validator names changed, configuration moved to ConfigDict, and serialization uses model_dump instead of dict. Pydantic v2 also has a Rust core with different performance characteristics. Treat v1 tutorials as migration references, not drop-in code.
- Does Pydantic validate types at runtime?
- Yes. Type hints are enforced at validation time, but Pydantic is lenient by default: it may coerce a numeric string to an integer. Use strict=True on the model or field when coercion would hide a client error.
- Should validation rules enforce authorization?
- No. Pydantic validates shape, type, and format. Authorization depends on the current user and the resource being accessed, so it belongs in the service or route layer after the input is parsed.
Interactive Tools for This Topic
Report a problem with this articleOpens a pre-filled issue on GitHub.