With the following FastAPI backend:
from enum import Enum
from fastapi import FastAPI
class MyNumber(int, Enum):
ONE = 1
TWO = 2
THREE = 3
app = FastAPI()
@app.get("/add/{a}/{b}")
async def get_model(a: MyNumber, b: MyNumber):
return {"sum": a + b}
When a GET operation is done:
curl -X 'GET' \
'http://127.0.0.1:8000/add/2/3' \
-H 'accept: application/json'
Returns the following:
{
"detail": [
{
"loc": [
"path",
"a"
],
"msg": "value is not a valid enumeration member; permitted: 1, 2, 3",
"type": "type_error.enum",
"ctx": {
"enum_values": [
1,
2,
3
]
}
},
{
"loc": [
"path",
"b"
],
"msg": "value is not a valid enumeration member; permitted: 1, 2, 3",
"type": "type_error.enum",
"ctx": {
"enum_values": [
1,
2,
3
]
}
}
]
}
Why is this the case? Even the Swagger UI does recognize the possible values as integers:
I have tried the solution of using IntEnum instead (source), and I can confirm that it works, but still - why does it have to be this way?
The enum.py source code defines IntEnum as:
class IntEnum(int, Enum):
"""Enum where members are also (and must be) ints"""
