Field types and constraints help you control what kind of data your app accepts. They make sure the data fits rules you set, like length or value limits.
Field types and constraints in FastAPI
from pydantic import BaseModel, Field class Item(BaseModel): name: str = Field(..., min_length=3, max_length=50, description="Name of the item") price: float = Field(..., gt=0, description="Price must be greater than zero") tags: list[str] = Field(default_factory=list, description="List of tags")
Use Field() to add rules like minimum length or greater than checks.
The ... means the field is required.
from pydantic import BaseModel, Field class User(BaseModel): username: str = Field(..., min_length=4, max_length=20) age: int = Field(..., ge=18, le=100)
from pydantic import BaseModel, Field class Product(BaseModel): name: str price: float = Field(gt=0) description: str | None = Field(default=None, max_length=300)
from pydantic import BaseModel, Field class BlogPost(BaseModel): title: str = Field(..., min_length=5) content: str published: bool = Field(default=False)
This FastAPI app defines an Item model with rules on name length and price value. The POST endpoint accepts an item and returns its data.
from fastapi import FastAPI from pydantic import BaseModel, Field app = FastAPI() class Item(BaseModel): name: str = Field(..., min_length=3, max_length=50, description="Name of the item") price: float = Field(..., gt=0, description="Price must be greater than zero") tags: list[str] = Field(default_factory=list, description="List of tags") @app.post("/items/") async def create_item(item: Item): return {"item_name": item.name, "item_price": item.price, "item_tags": item.tags}
Constraints like min_length, max_length, gt (greater than), and ge (greater or equal) help validate data easily.
Use default_factory=list to set an empty list as default to avoid mutable default arguments issues.
Descriptions in Field() help generate clear API docs automatically.
Field types and constraints ensure your app gets the right kind of data.
You can require fields, limit their size or value, and provide helpful descriptions.
FastAPI uses Pydantic models with Field() to make validation simple and automatic.