[Python] FastAPI + Enum validation on endpoint

Discussão em 'Python' iniciado por Stack, Julho 3, 2025.

  1. Stack

    Stack Membro Participativo

    I have a custom enum class:

    class CustomEnum(Enum):
    ONE = 1
    TWO = 2


    I have a fastapi endpoint:

    @router.post(...)
    async def example(request: Request, param: CustomEnum = Body(...)):
    print(param.value) # should return the int


    When the payload looks like this:

    {
    "param": "ONE"
    }


    It throws me a Bad data - param: value is not a valid enumeration member; permitted: 1, 2

    The UI and the BE should communicate via strings but I need to quickly know that "ONE" means 1. I thought an enum here would be best. Am I missing something here?

    Continue reading...

Compartilhe esta Página