-
Hello, new to Pydantic & FastAPI - I have an Enum:
Which I use to define a Model such as:
And I have a request hander that looks like:
When I submit a POST to my handler, that looks like:
I receive the following error:
How should I be better handling this to map whatever strings (colors in this case) to the correct Enum values to be validated? Thank you in advance |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
This can be resolved. I ended up moving this changing my Palette color attribute to be that of type string, but still handle the type checking at the validator which seems to work fine. |
Beta Was this translation helpful? Give feedback.
-
You can have no validator at all 😃 This works fine and converts the JSON strings into the corresponding enum members: from enum import Enum
from fastapi import FastAPI
from pydantic import BaseModel
class ColorEnum(str, Enum):
orange = "orange"
red = "red"
green = "green"
class Palette(BaseModel):
colors: list[ColorEnum]
app = FastAPI()
@app.post("/create")
def create_palette(item: Palette):
print(item)
print(item.colors) With the body you showed, this prints
It also handles invalid enum members, for example if you post {
"detail": [
{
"loc": [
"body",
"colors",
0
],
"msg": "value is not a valid enumeration member; permitted: 'orange', 'red', 'green'",
"type": "type_error.enum",
"ctx": {
"enum_values": [
"orange",
"red",
"green"
]
}
}
]
} |
Beta Was this translation helpful? Give feedback.
-
@brymon68 Have you tried using the
class Palette(BaseModel):
colors: List[ColorEnum]
class Config:
use_enum_values = True You could also use a class Palette(BaseModel):
colors: List[Literal["orange", "red", "green"]] |
Beta Was this translation helpful? Give feedback.
This can be resolved. I ended up moving this changing my Palette color attribute to be that of type string, but still handle the type checking at the validator which seems to work fine.