Custom validation lets you check data rules beyond basic types. It helps keep your app data clean and correct.
Custom validation with validator decorator in 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.
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
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
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.
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})
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.
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.
Practice
@validator decorator in a Pydantic model within FastAPI?Solution
Step 1: Understand the role of
The@validator@validatordecorator is used inside Pydantic models to add custom validation logic for fields.Step 2: Differentiate from other functionalities
It does not generate routes, define database relations, or format output JSON; those are handled elsewhere.Final Answer:
To add custom validation logic for model fields -> Option CQuick Check:
Custom validation = To add custom validation logic for model fields [OK]
- Confusing validation with route creation
- Thinking it formats output JSON
- Assuming it manages database relations
email in a Pydantic model?Solution
Step 1: Identify correct decorator usage
The correct decorator is@validator('field_name')with the field name as a string.Step 2: Check syntax correctness
@validator('email')\ndef check_email(cls, value):\n return value uses@validator('email')correctly; others use wrong decorator names or syntax.Final Answer:
@validator('email')\ndef check_email(cls, value):\n return value -> Option DQuick Check:
Correct decorator syntax = @validator('email')\ndef check_email(cls, value):\n return value [OK]
- Omitting quotes around field name
- Using wrong decorator name like @validate
- Using brackets [] instead of parentheses ()
age=15?
from pydantic import BaseModel, validator
class User(BaseModel):
age: int
@validator('age')
def check_age(cls, v):
if v < 18:
raise ValueError('Must be at least 18')
return v
user = User(age=15)Solution
Step 1: Analyze the validator logic
The validator checks ifageis less than 18 and raises aValueErrorif true.Step 2: Apply input value to validator
Sinceage=15is less than 18, the validator raises the error with the message.Final Answer:
A ValueError is raised with message 'Must be at least 18' -> Option AQuick Check:
Age < 18 triggers ValueError = A ValueError is raised with message 'Must be at least 18' [OK]
- Assuming instance is created despite validation error
- Thinking age auto-corrects to 18
- Confusing ValueError with TypeError
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 haveclsas the first parameter, then the value.Step 2: Identify missing parameter
The method only hasvalue, missingcls, causing a TypeError.Final Answer:
Missingclsparameter in validator method -> Option BQuick Check:
Validator method needs cls first = Missingclsparameter in validator method [OK]
- Omitting cls parameter
- Using wrong decorator name
- Forgetting to return the value
username field to ensure it is at least 3 characters long and contains only letters and numbers. Which validator implementation correctly achieves this?Solution
Step 1: Check length and character conditions
The username must be at least 3 characters and only letters or numbers.Step 2: Evaluate each option's validation logic
from pydantic import BaseModel, validator import re class User(BaseModel): username: str @validator('username') def valid_username(cls, v): if len(v) < 3 or not re.match(r'^[a-zA-Z0-9]+$', v): raise ValueError('Username must be 3+ chars and alphanumeric') return v correctly checks length & uses regex to allow letters and numbers only. Others either check wrong conditions or restrict letters only.Final Answer:
Option A correctly validates username length and alphanumeric characters -> Option AQuick Check:
Length >=3 and alphanumeric = from pydantic import BaseModel, validator import re class User(BaseModel): username: str @validator('username') def valid_username(cls, v): if len(v) < 3 or not re.match(r'^[a-zA-Z0-9]+$', v): raise ValueError('Username must be 3+ chars and alphanumeric') return v [OK]
- Using isalpha() instead of isalnum()
- Checking length incorrectly (greater than vs less than)
- Restricting to letters only when numbers allowed
Ready to prove it?
Pass the test and this pattern moves unknown
