Field validation rules help check if the data sent to your API is correct and safe. They stop wrong or missing information before it causes problems.
Field validation rules in FastAPI
from pydantic import BaseModel, Field class User(BaseModel): name: str = Field(..., min_length=2, max_length=50) age: int = Field(..., ge=1, le=120) email: str = Field(..., regex=r"^[\w\.-]+@[\w\.-]+\.\w{2,4}$")
Field(...) means the field is required.
You can add rules like min_length, max_length, ge (greater or equal), le (less or equal), and regex for patterns.
from pydantic import BaseModel, Field class Product(BaseModel): title: str = Field(..., min_length=3) price: float = Field(..., gt=0)
from pydantic import BaseModel, Field class User(BaseModel): username: str = Field(..., regex=r"^[a-zA-Z0-9_]+$") bio: str | None = Field(None, max_length=200)
This FastAPI app defines a User model with validation rules. When you send data to /users/, FastAPI checks the rules. If data is wrong, it returns clear errors. If data is good, it confirms user creation.
from fastapi import FastAPI from pydantic import BaseModel, Field from fastapi.responses import JSONResponse from fastapi.requests import Request from fastapi.exception_handlers import RequestValidationError app = FastAPI() class User(BaseModel): name: str = Field(..., min_length=2, max_length=50) age: int = Field(..., ge=1, le=120) email: str = Field(..., regex=r"^[\w\.-]+@[\w\.-]+\.\w{2,4}$") @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=422, content={"detail": exc.errors(), "body": exc.body}, ) @app.post("/users/") async def create_user(user: User): return {"message": f"User {user.name} created successfully!", "user": user.dict()}
Validation errors automatically return a 422 status with details.
Use Field(...) to make a field required, or Field(None) to make it optional.
Regex patterns must be raw strings (prefix with r) to avoid escape issues.
Field validation rules check data before your API uses it.
Use Field with options like min_length, max_length, ge, le, and regex.
FastAPI and Pydantic handle errors and give clear messages automatically.