FastAPI - ENUM type models not populated

30.3k views Asked by At

Below is my fastAPI code

from typing import Optional, Set

from fastapi import FastAPI
from pydantic import BaseModel, HttpUrl, Field
from enum import Enum

app = FastAPI()


class Status(Enum):
    RECEIVED = 'RECEIVED'
    CREATED = 'CREATED'
    CREATE_ERROR = 'CREATE_ERROR'


class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None
    tags: Set[str] = []
    status: Status = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    results = {"item_id": item_id, "item": item}
    return results

Below is the swagger doc generated. The Status is not shown. I am new to pydantic and i am not sure on how to show status in the docs

enter image description here

1

There are 1 answers

3
JPG On BEST ANSWER

create the Status class by inheriting from both str and Enum

class Status(str, Enum):
    RECEIVED = 'RECEIVED'
    CREATED = 'CREATED'
    CREATE_ERROR = 'CREATE_ERROR'

References

  1. Working with Python enumerations--(FastAPI doc)
  2. [BUG] docs don't show nested enum attribute for body--(Issue #329)