Custom validators help check if data fits special rules you make. This keeps your app safe and correct.
Custom validators in 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.
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
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
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
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.
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}'})
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.
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.
Practice
@validator in FastAPI models?Solution
Step 1: Understand the role of
The@validator@validatordecorator is used to add custom validation logic to model fields in FastAPI.Step 2: Identify the purpose of validation
Validation ensures that the data meets specific rules before the app processes it, helping keep input correct and safe.Final Answer:
To add custom rules that check if input data is valid -> Option CQuick Check:
Custom validation = check input rules [OK]
- Confusing validators with database connectors
- Thinking validators generate docs
- Assuming validators change response style
age?Solution
Step 1: Recall the correct decorator syntax
FastAPI uses Pydantic's@validatordecorator with the field name as a string argument.Step 2: Match the function definition style
The validator function must be a class method with parametersclsandvalue.Final Answer:
@validator('age')\ndef check_age(cls, value): -> Option AQuick Check:
Use @validator('field') with cls, value [OK]
- Using @validate instead of @validator
- Missing the field name in decorator
- Wrong function parameters
age is set to 15?
from pydantic import BaseModel, validator
class User(BaseModel):
age: int
@validator('age')
def check_age(cls, value):
if value < 18:
raise ValueError('Must be 18 or older')
return value
try:
user = User(age=15)
except Exception as e:
print(e)Solution
Step 1: Analyze the validator logic
The validator checks ifageis less than 18 and raises a ValueError if true.Step 2: Check the input value
Sinceage=15is less than 18, the validator raises the error.Final Answer:
Must be 18 or older -> Option AQuick Check:
Age < 18 triggers ValueError [OK]
- Assuming object creates despite validation error
- Confusing ValueError with TypeError
- Ignoring the exception handling block
from pydantic import BaseModel, validator
class Product(BaseModel):
price: float
@validator('price')
def check_price(value):
if value <= 0:
raise ValueError('Price must be positive')
return valueSolution
Step 1: Check validator method signature
Validator methods must acceptclsas the first parameter, thenvalue.Step 2: Identify missing parameter
The methodcheck_priceonly hasvalue, missingcls.Final Answer:
Missingclsparameter in validator method -> Option BQuick Check:
Validator needs cls, value parameters [OK]
- Omitting cls parameter
- Using wrong decorator name
- Returning None instead of value
from pydantic import BaseModel, validator
class User(BaseModel):
username: str
@validator('username')
def validate_username(cls, value):
# Fill in validation logic here
passSolution
Step 1: Understand validation requirements
The username must be lowercase and at least 3 characters long.Step 2: Check each option logic
if value.islower() and len(value) >= 3:\n return value\nraise ValueError('Username invalid') correctly checks both conditions and raises error if not met, returning value otherwise.Final Answer:
if value.islower() and len(value) >= 3:\n return value\nraise ValueError('Username invalid') -> Option DQuick Check:
Check both conditions, raise error if false [OK]
- Using 'or' instead of 'and' causing wrong logic
- Returning value inside else but missing return in if
- Incorrect length comparison operators
Ready to prove it?
Pass the test and this pattern moves unknown
