How to add custom validators that adhere to spectree's validation? #361
Answered
by
kemingy
guilhermeschmitd-hotmart
asked this question in
Q&A
-
I have model that requires further validation according to business rules, such as the following example. When this validation fails, I'd like my API to return error messages in the same way class Item(BaseModel):
item_id: int
name: Annotated[str, Field(min_length=3)]
amount: Annotated[int, Field(gt=0)]
price: Annotated[float, Field(gt=0)]
class ShoppingCart(BaseModel):
items: Annotated[Sequence[Item], Field(min_items=1)]
@validator('items')
@classmethod
def validate_items(cls, value):
if len({v['item_id'] for v in value}) < len(value):
raise Exception('A cart cannot have duplicate items. Use amounts instead.') # What should I do here?
return value Can this be achieved or should I use a separate validation step within the endpoint logic? |
Beta Was this translation helpful? Give feedback.
Answered by
kemingy
Nov 14, 2023
Replies: 1 comment 1 reply
-
You can raise |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
guilhermeschmitd-hotmart
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can raise
ValueError
here. It will be converted to a ValidationError in pydantic. Then it will be processed by spectree like the usual validation errors.