FastAPI: Validating Models with Pydantic's Field
Pydantic's `Field` adds guardrails directly to your data model's attributes. Use it to enforce constraints like string length (`max_length=50`) or numeric ranges (`gt=0`), making your models self-validating.
WHY IT EXISTS: FastAPI relies on Pydantic models to define the shape of incoming data. But just defining a type (like str or int) is often not enough. Real-world applications need to enforce business rules, like a price being positive or a description having a character limit. Field solves this by letting you declare these rules within the model itself, co-locating data shape and data rules.
THE MENTAL MODEL: Think of a Pydantic model as a blueprint for your data. Using Field is like adding specific instructions and constraints directly onto that blueprint. Instead of having separate validation logic scattered in your code, the validation rules live with the data definition, making the model a single source of truth for both its shape and its validity.
HOW IT WORKS: You import Field from Pydantic and use it as the default value for a model attribute. You can provide a default value as the first argument, or use keyword arguments to define validation rules (max_length, gt, lt) and metadata (title, description). When FastAPI receives a request body matching this model, Pydantic automatically runs these validations and returns a clear, structured error if any rule is violated.
WHEN TO USE IT: Use Field whenever you define a Pydantic model for a request body and need more than just type checking. It's perfect for setting maximum string lengths, defining numeric constraints (e.g., greater than zero), providing example values for documentation, and adding descriptive titles or descriptions that will automatically appear in your OpenAPI (Swagger UI) documentation.
WHEN NOT TO USE IT: Do not use Field to validate path parameters or query parameters directly in your path operation function signature. For those, you must use Path and Query from FastAPI. Field is specifically for attributes inside a Pydantic model. Using it elsewhere will not work as expected and is a common source of confusion.
ONE CANONICAL EXAMPLE: Consider an Item model for an e-commerce API. A description attribute can be defined as description: str | None = Field(default=None, title="Item Description", max_length=300). A price attribute can be price: float = Field(gt=0, description="Price must be a positive value."). This ensures any incoming Item object has an optional description no longer than 300 characters and a price that is always greater than zero, with these rules enforced automatically by FastAPI.
Read the original → fastapi.tiangolo.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.