Fastapi: [BUG] List of Enum arguments have an extra wrong argument

Created on 7 May 2020  路  4Comments  路  Source: tiangolo/fastapi

Describe the bug

The parsed /docs page includes a "--" option which leads to an invalid query when using an Enum derived class.

To Reproduce

  1. Create a file with:
import enum
from fastapi import FastAPI

app = FastAPI()

class Fruit(str, enum.Enum):
    apple: str = "APPLE"
    pear: str = "PEAR"
    banana: str = "BANANA"
    strawberry: str = "STRAWBERRY"


@app.get("/fruit", response_model=List[Fruit])
async def list_fruit(fruits: List[Fruit] = Query(None)):
    return fruits

Then call the http method with the "--" option

Expected behavior

Would expect the same behavior of not having specified any query argument fruits at all.

Error

The error message:

{
  "detail": [
    {
      "loc": [
        "query",
        "fruits",
        0
      ],
      "msg": "value is not a valid enumeration member; permitted: 'APPLE', 'PEAR', 'BANANA', 'STRAWBERRY'",
      "type": "type_error.enum",
      "ctx": {
        "enum_values": [
          "APPLE",
          "PEAR",
          "BANANA",
          "STRAWBERRY"
        ]
      }
    }
  ]
}

Screenshots

image

Environment

  • OS: Windows
  • FastAPI Version 0.54.1
  • Python version: 3.7.4

Additional context

Add any other context about the problem here.

answered bug

Most helpful comment

Here is a potential work around:

In your Enum add a new value called none (or something equivalent) that is set to an empty string ''. Now when you select the -- value in swagger the endpoint will perform as expected.

The only problem with this is that when you select the -- it now selects the empty string as well (so two options are highlighted).

swagger

While not breaking or anything this is confusing from a usability perspective.

All 4 comments

I may be wrong but the -- option appears to be an intentional design of Swagger UI, not anything specific to fastapi. the validation fails because starlette now treats these empty query param flags (?fruits or ?fruits=) as params with empty string values (see #1147 and encode/starlette#672)

Thanks for the help here @obataku !

Yeah, that would probably be an issue to report to Swagger UI, it doesn't really depend on FastAPI.

Here is a potential work around:

In your Enum add a new value called none (or something equivalent) that is set to an empty string ''. Now when you select the -- value in swagger the endpoint will perform as expected.

The only problem with this is that when you select the -- it now selects the empty string as well (so two options are highlighted).

swagger

While not breaking or anything this is confusing from a usability perspective.

Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues.

Was this page helpful?
0 / 5 - 0 ratings