0
0
FastAPIframework~5 mins

Custom validation with validator decorator in FastAPI

Choose your learning style9 modes available
Introduction

Custom validation lets you check data rules beyond basic types. It helps keep your app data clean and correct.

When you want to check if a string matches a special pattern like a phone number.
When you need to ensure a number is within a certain range.
When you want to validate one field based on another field's value.
When built-in validations are not enough for your data rules.
Syntax
FastAPI
from pydantic import BaseModel, validator

class ModelName(BaseModel):
    field_name: field_type

    @validator('field_name')
    def check_field_name(cls, value):
        # validation logic
        valid = True  # replace with actual validation condition
        if not valid:
            raise ValueError('error message')
        return value

The @validator decorator is used inside a Pydantic model class.

The validator method must return the value if it passes validation.

Examples
This checks that the username is not just spaces or empty.
FastAPI
from pydantic import BaseModel, validator

class User(BaseModel):
    username: str

    @validator('username')
    def username_must_not_be_empty(cls, v):
        if not v.strip():
            raise ValueError('Username cannot be empty')
        return v
This ensures the price is greater than zero.
FastAPI
from pydantic import BaseModel, validator

class Product(BaseModel):
    price: float

    @validator('price')
    def price_must_be_positive(cls, v):
        if v <= 0:
            raise ValueError('Price must be positive')
        return v
Sample Program

This FastAPI app defines an Item model with a custom validator that checks quantity is positive. If you send a POST request with quantity 0 or less, it returns an error. Otherwise, it returns the item data.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel, validator
from fastapi.responses import JSONResponse

app = FastAPI()

class Item(BaseModel):
    name: str
    quantity: int

    @validator('quantity')
    def quantity_must_be_positive(cls, v):
        if v <= 0:
            raise ValueError('Quantity must be greater than zero')
        return v

@app.post('/items/')
async def create_item(item: Item):
    return JSONResponse(content={'name': item.name, 'quantity': item.quantity})
OutputSuccess
Important Notes

Validators run automatically when you create or update model instances.

You can add multiple validators for different fields in the same model.

Raise ValueError with a clear message to help users fix input.

Summary

Use @validator inside Pydantic models to add custom checks.

Validators help keep your data clean and your app safe.

Always return the value if it passes validation or raise an error if not.