pythonenumsmodelfastapipydantic

Pydantic model : add case insensitive field


I have a confirm field that accepts yes ( case insensitive ) input from the user. This is how I am implementing it :

class ConfirmEnum(str, Enum):
    yes = "yes"
    Yes = "Yes"
    YES = "YES"
class OtherFields(CamelModel):
    data: int
    confirm: Optional[ConfirmEnum]
    ...other fileds added here
async def pet_classes(
    pet_service: PetService = Depends(
        PetService
    ),
    confirm: ConfirmEnum = Query(None, alias="confirm"),
    response: Response = status.HTTP_200_OK,
):

I do not think it is the right way to do it, or there must be better way than to just use enum.


Solution

  • I cannot comment on Pydantic, but your enum should be:

    class ConfirmEnum(str, Enum):
        YES = "YES"
        #
        @classmethod
        def _missing_(cls, value):
            try:
                return cls[value.upper()]
            except KeyError:
                pass
    

    The try/except is used so you don't end up with a double stack trace when an invalid key is used.