TypeError:类型“type”的对象不可 JSON 序列化

Ank*_*ita 2 python swagger swagger-ui openapi fastapi

该代码在 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"
        )
Run Code Online (Sandbox Code Playgroud)

收到错误:

TypeError: Object of type 'type' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 5

问题

\n

您在控制台中收到以下错误的原因(请注意,其他原因也可能引发此错误\xe2\x80\x94请参阅此处):

\n
TypeError: Object of type \'type\' is not JSON serializable\n
Run Code Online (Sandbox Code Playgroud)\n

尝试加载 OpenAPI/Swagger UI 自动文档时,以及浏览器中出现以下错误/docs

\n
Fetch error\nInternal Server Error /openapi.json\n
Run Code Online (Sandbox Code Playgroud)\n

是由于您的代码中的以下行所致:

\n
TypeError: Object of type \'type\' is not JSON serializable\n
Run Code Online (Sandbox Code Playgroud)\n

解决方案

\n

当声明Header参数(或任何其他类型的参数,即Path,,,,等)时,传递给Query构造函数(即方法)的第一个值是值,它可以是基于您为参数指定的类型\xe2\x80\x94(在您的情况下)可能是某个字符串值,例如 ,而不是类型) 。由于您将参数定义为,因此您可以简单地作为默认值传递:CookieHeader__init__ defaultNone\'some-api-key\'strOptionalNone

\n
Fetch error\nInternal Server Error /openapi.json\n
Run Code Online (Sandbox Code Playgroud)\n

请查看这个答案这个答案以获取有关 FastAPI 中参数的更多详细信息Optional

\n