Fastapi: [BUG] docs don't show nested enum attribute for body

Created on 23 Jun 2019  路  6Comments  路  Source: tiangolo/fastapi

Describe the bug
I have a post method with the body as pydantic object, with one attribute as Enum object; All validation works perfectly; However, two independent (?) issues occur:

  1. complaint.dict() generates a dictionary - but does not flatten nested enum object into string. I am getting this is beyound the idea of dict(), but would be nice to have something that flattens the whole entity;
  2. complaint_type attribute does not show up on the swagger

To Reproduce
example coe snippet:

class ComplaintType(Enum):
    other = 'other'
    commercial = "commercial"
    house = "house"
    park = "park"
    residential = "residential"
    street = "street"
    vehicle = "vehicle"


class Complaint(BaseModel):
    complaint_type:ComplaintType
    timestamp:datetime = datetime.now()
    lat:float
    lon:float
    description:str

Expected behavior
I expected

  1. complaint_type to be on a swagger and in the schema as (I guess) "oneOf" element
  2. be able to flatten Pydantic object into a fully json-able dictionary (converting enum objects into strings)

Environment:

  • OS: macOS
  • FastAPI Version 0.30.0

    • Python version 3,7.3

bug

Most helpful comment

Can you test whether this fixes it:

class Geoaccuracy(str, Enum):
    unknown = "unknown"
    latlng = "latlng"
    place = "place"
    city = "city"
    country = "country"

This works for me and correctly shows in SwaggerDocs. In your case, you've specified type Enum but not which type for Enum (looks like its str, too).

All 6 comments

Can you test whether this fixes it:

class Geoaccuracy(str, Enum):
    unknown = "unknown"
    latlng = "latlng"
    place = "place"
    city = "city"
    country = "country"

This works for me and correctly shows in SwaggerDocs. In your case, you've specified type Enum but not which type for Enum (looks like its str, too).

thanks! that did the trick with the docs!.

I realize the other question is rather for Pydantic repo, but how should I automatically convert all nested enum values to corresponding simple values, instead? I see FastAPI does that, but wasn't able to track the exact code line

Thanks @Sieboldianus for your help!

@Casyfill it's actually an issue in Swagger UI, by adding the str, the generated JSON Schema also includes the type "string", and Swagger UI requires it to be able to display it.

It's actually a bug in Swagger UI, Pydantic and FastAPI are generating a valid OpenAPI schema.

But I should update the Enum examples in the docs.

Update, I just updated the docs, to use Enums that inherit from str: https://fastapi.tiangolo.com/tutorial/path-params/#working-with-python-enumerations

Thank you both! That makes a lot of sense - somehow I never used Enum before, so - good to know!

Thanks @Casyfill for reporting back and closing the issue! :cake:

Was this page helpful?
0 / 5 - 0 ratings