-
First Check
Commit to Help
Example Codefrom enum import Enum
from fastapi import Depends, FastAPI, HTTPException
app = FastAPI()
class Names(str, Enum):
Bob = "Bob"
Jack = "Jack"
async def name_parameter(name: str) -> Names:
try:
return Names(name)
except ValueError:
raise HTTPException(detail="wrong name", status_code=422)
@app.get("/")
async def root(name_valid_representation: Names,
name_wrong_representation: Names = Depends(name_parameter)
):
return {"message": f"Hello"}DescriptionFor my application, I use several I need to customize the error messages automatically returned by pydantic. For this, I use a parameter of type This works, but I noticed that when using Depends, the dropdown list with the allowed values no longer appears. Is there a way to display this dropdown list while customizing the error message? I also explored Thanks in advance for your answers Operating SystemLinux Operating System DetailsNo response FastAPI Version0.94.0 Python Version3.10.6 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
|
The reason is because your dependency isnt taking an Enum any more it is taking a string so the openapi generator reflects that. A better approach might be to write a custom exception handler to handle the exception from pydantic to return what you would prefer. You can read some in the docs here https://fastapi.tiangolo.com/tutorial/handling-errors/#override-request-validation-exceptions Then you wont need the dependency and your endpoint can simply list the enum type like you do with name_valid_representation. |
Beta Was this translation helpful? Give feedback.
-
|
I have the same issue than you, with all kind of usages of Enums. The Swagger UI autodoc always sets the dropdown menu as "disabled". For example this : from fastapi import FastAPI
from enum import Enum
app = FastAPI()
class Country(str, Enum):
eu = "eu"
us = "us"
@app.get("/")
def get_something(country: Country = Country.eu):
return {"country": country.value}This is the screenshot. You cannot see it but hovering over the dropdown leads my mouse icon to turn into a "forbidden" icon. The same happens for the example in the doc : https://fastapi.tiangolo.com/tutorial/path-params/?h=enum#working-with-python-enumerations I tried to do the same with an explicit My versions:
|
Beta Was this translation helpful? Give feedback.



The reason is because your dependency isnt taking an Enum any more it is taking a string so the openapi generator reflects that.
A better approach might be to write a custom exception handler to handle the exception from pydantic to return what you would prefer.
You can read some in the docs here https://fastapi.tiangolo.com/tutorial/handling-errors/#override-request-validation-exceptions
Then you wont need the dependency and your endpoint can simply list the enum type like you do with name_valid_representation.