0
0
FastAPIframework~5 mins

Field validation rules in FastAPI

Choose your learning style9 modes available
Introduction

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.

When you want to make sure a user's email is in the right format.
When you need to check that a password is long enough.
When you want to limit a number to a certain range, like age between 1 and 120.
When you want to require some fields and make others optional.
When you want to give clear error messages if data is wrong.
Syntax
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.

Examples
This example requires a product title with at least 3 characters and a price greater than 0.
FastAPI
from pydantic import BaseModel, Field

class Product(BaseModel):
    title: str = Field(..., min_length=3)
    price: float = Field(..., gt=0)
Here, username must match the pattern (letters, numbers, underscores). Bio is optional but limited to 200 characters.
FastAPI
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)
Sample Program

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.

FastAPI
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()}
OutputSuccess
Important Notes

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.

Summary

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.