Platform 08 · Study guide
Validate request payloads with pipe rules before they reach your services.
from tpy.validation import validate, ValidationException, Validator from tpy.http import ApiResponse
No extra dependency. Use in controllers/services on incoming dict payloads.
try:
data = validate(
payload,
{
"email": "required|email",
"age": "required|integer|min:18",
"password": "required|confirmed",
"role": "nullable|in:admin,user",
},
)
except ValidationException as exc:
return ApiResponse.validation_error(exc)
# data is the cleaned/accepted input
return ApiResponse.success(service.create(data))
required|email|min:3).ValidationException with per-field messages.ApiResponse.validation_error(exc) turns that into HTTP 422 JSON.| Rule | Example | Meaning |
|---|---|---|
required | required | Must be present/non-empty |
nullable | nullable|email | Skip other rules when empty |
email / uuid / url | email | Format checks |
integer / numeric / boolean | integer | Type checks |
min / max / between | min:18 | Bounds |
in / not_in | in:admin,user | Allow-list |
confirmed | confirmed | Needs field_confirmation |
regex | regex:^[A-Z]+$ | Pattern |
Validator.extend(
"odd",
lambda attr, value, data: int(value) % 2 == 1,
"Value must be odd.",
)
Validator.make({"n": 3}, {"n": "odd"}).validate()