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.
Questo esercizio fa parte del corso
Deploying AI into Production with FastAPI
Istruzioni dell'esercizio
- 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.
Esercizio pratico interattivo
Prova a risolvere questo esercizio completando il codice di esempio.
# 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