代码在Postman正常运行,生成OpenAPI/Swagger UI文档时遇JSON序列化错误
FastAPI生成OpenAPI文档时JSON序列化错误的解决
问题场景
代码在Postman中可正常运行并返回有效响应,但生成OpenAPI/Swagger UI自动文档时触发错误:
类型错误:'type'类型的对象无法被JSON序列化
涉及代码:
from enum import Enum from typing import Union from fastapi import FastAPI, Header, HTTPException, status from pydantic import BaseModel app = FastAPI() info_dict = [] 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" )
错误原因
- Header参数默认值错误:
apikey: Union[str, None] = Header(str)中,Header()的参数传了str类型对象,而非实际的字符串或None。FastAPI生成OpenAPI文档时会尝试序列化这个默认值,而类型对象无法被JSON序列化,直接触发报错。 - 代码语法错误:
alias2 = AppInfo(info="Plumbus", id=123, , role=info.role)里多了一个逗号,虽然部分解释器可能忽略,但属于不规范写法,需修正。
修复方案
- 修正Header参数的默认值,将
Header(str)改为Header(None),符合Union[str, None]的类型定义:async def create(info: Info, apikey: Union[str, None] = Header(None)): - 移除
alias2初始化语句中的多余逗号:alias2 = AppInfo(info="Plumbus", id=123, role=info.role)
修复后完整代码
from enum import Enum from typing import Union from fastapi import FastAPI, Header, HTTPException, status from pydantic import BaseModel app = FastAPI() info_dict = [] 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(None)): 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" )
修复后重新启动服务,即可正常生成OpenAPI/Swagger UI文档,同时不影响Postman的正常请求。
内容的提问来源于stack exchange,提问作者Tanu
相关产品推荐
相关产品推荐

