Custom model validator
You have an API to update inventory and have been asked to surface a user-friendly error message when negative quantities are input.
The RequestValidationError exception has been pre-loaded for you.
Deze oefening maakt deel uit van de cursus
Deploying AI into Production with FastAPI
Oefeninstructies
- Import the annotation for custom model validation.
- Implement a custom model validation that runs
"after"the default model validations. - Raise a
RequestValidationErrorexception to surface validation errors to the API user.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
# Import annotation for custom validation
from pydantic import BaseModel, ____
class InventoryRecord(BaseModel):
name: str
quantity: int
# Create custom validator that runs after default validation
@model_validator(mode="____")
def validate_after(self):
if len(self.quantity) < 0:
# Raise request validation error
raise ____(
"Negative quantity is not allowed!"
)
return self