BaşlayınÜcretsiz Başlayın

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.

Bu egzersiz

Deploying AI into Production with FastAPI

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

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

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

# 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
Kodu Düzenle ve Çalıştır