Get startedGet started for free

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.

This exercise is part of the course

Deploying AI into Production with FastAPI

View Course

Exercise instructions

  • Import the annotation for custom model validation.
  • Implement a custom model validation that runs after the default model validations.
  • Raise a request validation exception to surface validation errors to the API user.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# 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
Edit and Run Code