Pydantic - Validation Does not Happen

I am quite new to using Pydantic.

The Issue I am facing right now is that the Model Below is not raising the Expected Exception when the value is out of range.

For example, if you pass -1 into this model it should ideally raise an HTTPException. but nothing happens

I am not sure where I might be going wrong.

Any Advice would be great.

class GetInput:
    """
    for the fields endpoint
    """

    def __init__(self,
                 rank: Optional[int] = None,
                 interval: Optional[int] = None):

        self.rank = rank
        self.interval = interval

    @validator('rank')
    def check_if_rank_in_range(cls, v):
        """
        check if input rank is within range
        """
        if not 0 < v < 1000001:

            raise HTTPException(
                status_code=400, detail="Rank Value Must be within range (0,1000000)")
        return v

    @validator('interval')
    def check_if_interval_in_range(cls, v):
        """
        check if input rank is within range
        """
        if not 0 < v < 1000001:

            raise HTTPException(
                status_code=400, detail="Interval Value Must be within range (0,1000000)")
        return v

The FastAPI Endpoint

@router.get('fields/',status_code=200)
def get_data(params: GetInput = Depends()):
    
    if params.rank:
        result = get_info_by_rank(params.rank)

    elif params.interval:

        result = get_info_by_interval(params.interval)
    
    return result

Upvotes: 6

Views: 18409

Answers (2)

Sunchock
Sunchock

Reputation: 378

For pydantic 2.7.1, validator has been deprecated for field_validator

Heres an example :

#!/usr/bin/env python3
# Python imports
from typing import Optional
# Packages imports
from pydantic import BaseModel, field_validator

class B(BaseModel):
    var3: str
    var4: str

class A(BaseModel):
    var1: int
    var2: Optional[B] = None

    @field_validator('var2', mode='before')
    def check_empty(cls, value):
        print("check_empty", cls, value)
        return value or None

if __name__ == "__main__":
    data = {
        "var1": 1,
        "var2": {}
    }
    result = A.model_validate(data)
    print(result)

Upvotes: 0

class GetInput(BaseModel):

    rank: Optional[int]=None
    interval: Optional[int]=None
    
    @validator("*")
    def check_range(cls, v):
        if v: 
            if not 0 < v < 1000001:
                raise HTTPException(status_code=400, detail="Value Must be within range (0,1000000)")
            return v
  • the validator was not working due to not Inheriting the BaseModel Class
  • When the BaseModel Class would get inherited it would throw an error if either of the values is empty thus the additional if statement.

Upvotes: 5

Related Questions