Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI - ENUM type models not populated

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

like image 992
VamsiKrishna Avatar asked Oct 01 '20 17:10

VamsiKrishna


1 Answers

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)
like image 176
JPG Avatar answered Oct 02 '22 10:10

JPG