类型错误:类型为"类型"的对象不可 JSON 序列化



代码在Postman中工作良好,并提供有效的响应,但无法生成OpenAPI/Swagger UI自动文档。

class Role(str, Enum):
Internal = "internal"
External = "external"

class Info(BaseModel):
id: int
role: Role
class AppInfo(Info):
info: str

@app.post("/api/v1/create", status_code=status.HTTP_200_OK)
async def create(info: Info, apikey: Union[str, None] = Header(str)):
if info:
alias1 = AppInfo(info="Portal Gun", id=123, role=info.role)
alias2 = AppInfo(info="Plumbus", id=123, , role=info.role)
info_dict.append(alias1.dict())
info_dict.append(alias2.dict())

return {"data": info_dict}
else:

raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Please provide the input"
)

错误收到:

TypeError: Object of type 'type' is not JSON serializable

问题

在控制台中出现以下错误的原因(注意,此错误也可能由其他原因引发—参见此处):

TypeError: Object of type 'type' is not JSON serializable

以及下面的错误在浏览器中,当试图加载OpenAPI/Swagger UI autodocs在/docs:

Fetch error
Internal Server Error /openapi.json

是由于代码中的以下行:

apikey: Union[str, None] = Header(str)
^^^

解决方案当声明Header参数(或任何其他类型的参数,即Path,Query,Cookie等)时,传递给Header类构造器(即__init__方法)的第一个值是default值,该值可以是None或基于您为参数指定的类型的某些默认值-在您的情况下,可以是一些字符串值,例如'some-api-key'而不是类型为str)。因为您将参数定义为Optional,所以您可以简单地将None作为默认值传递:

apikey: Union[str, None] = Header(None)

关于FastAPI中Optional参数的更多细节,请查看这个答案和这个答案。

我想问题可能出在:

apikey: Union[str, None] = Header(str)

中的async函数create()

也许函数或类Header()不接受str作为输入?

虽然我真的不知道这个函数是做什么的,但//它来自哪个库。