18

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

VamsiKrishna
  • 751
  • 6
  • 14
  • 29

1 Answers1

44

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)
JPG
  • 82,442
  • 19
  • 127
  • 206
  • 1
    I am using this example but I get 422 Unprocessable Entity – Tlaloc-ES Jun 09 '22 at 21:18
  • How can we add Enum options via code script? I would like to fetch the options from DB using Python – Hossein Kalbasi Sep 17 '22 at 17:19
  • You can create an `Enum` on the fly using `CustomEnum = Enum("CustomEnum", custom_enum_values)` (where `custom_enum_values` is a `Dict[str,str]`) and then just use the `CustomEnum` type in the `BaseModel`: https://github.com/tiangolo/fastapi/issues/13 – NeilG Feb 27 '23 at 09:46