[Python] How to make case insensitive choices using Python's enum and FastAPI?

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

  1. Stack

    Stack Membro Participativo

    I have this application:

    import enum
    from typing import Annotated, Literal

    import uvicorn
    from fastapi import FastAPI, Query, Depends
    from pydantic import BaseModel

    app = FastAPI()


    class MyEnum(enum.Enum):
    ab = "ab"
    cd = "cd"


    class MyInput(BaseModel):
    q: Annotated[MyEnum, Query(...)]


    @app.get("/")
    def test(inp: MyInput = Depends()):
    return "Hello world"


    def main():
    uvicorn.run("run:app", host="0.0.0.0", reload=True, port=8001)


    if __name__ == "__main__":
    main()


    curl http://127.0.0.1:8001/?q=ab or curl http://127.0.0.1:8001/?q=cd returns "Hello World"

    But any of these

    • curl http://127.0.0.1:8001/?q=aB
    • curl http://127.0.0.1:8001/?q=AB
    • curl http://127.0.0.1:8001/?q=Cd
    • etc

    returns 422Unprocessable Entity which makes sense.

    How can I make this validation case insensitive?

    Continue reading...

Compartilhe esta Página