Custom validators help check if data fits special rules you make. This keeps your app safe and correct.
0
0
Custom validators in FastAPI
Introduction
You want to check if a username has no spaces.
You need to ensure a password has a mix of letters and numbers.
You want to confirm an email ends with a certain domain.
You want to make sure a date is not in the past.
You want to validate a custom ID format.
Syntax
FastAPI
from pydantic import BaseModel, validator class MyModel(BaseModel): field_name: str @validator('field_name') def check_field(cls, value): # your custom check here if not value.isalpha(): raise ValueError('Only letters allowed') return value
Use @validator('field_name') above a method to check that field.
The method gets the value and must return it if valid or raise ValueError if not.
Examples
This checks the username has no spaces.
FastAPI
from pydantic import BaseModel, validator class User(BaseModel): username: str @validator('username') def no_spaces(cls, v): if ' ' in v: raise ValueError('No spaces allowed') return v
This ensures the price is more than zero.
FastAPI
from pydantic import BaseModel, validator class Product(BaseModel): price: float @validator('price') def positive_price(cls, v): if v <= 0: raise ValueError('Price must be positive') return v
This forces the email to end with '@gmail.com'.
FastAPI
from pydantic import BaseModel, validator class EmailCheck(BaseModel): email: str @validator('email') def must_be_gmail(cls, v): if not v.endswith('@gmail.com'): raise ValueError('Email must be gmail') return v
Sample Program
This FastAPI app has a User model with two custom checks: username cannot have spaces, and age must be 18 or older. If data fails, FastAPI returns an error automatically.
FastAPI
from fastapi import FastAPI from pydantic import BaseModel, validator from fastapi.responses import JSONResponse app = FastAPI() class User(BaseModel): username: str age: int @validator('username') def username_no_spaces(cls, v): if ' ' in v: raise ValueError('Username cannot contain spaces') return v @validator('age') def age_must_be_adult(cls, v): if v < 18: raise ValueError('Must be at least 18 years old') return v @app.post('/users') async def create_user(user: User): return JSONResponse(content={'message': f'User {user.username} created, age {user.age}'})
OutputSuccess
Important Notes
Custom validators run automatically when data is received or created.
Raise ValueError with a clear message to help users fix input.
You can add multiple validators for different fields or the same field.
Summary
Custom validators check data with your own rules.
They help keep your app safe and user input correct.
Use @validator on model fields to add these checks.