FastApi Swagger 序列化问题
问题
错误现象:
- fastapi的 swagger 界面无法正常打开
- 控制台报错:
raise PydanticInvalidForJsonSchema(f'Cannot generate a JsonSchema for {error_info}')
详细报错:
File "d:\Envs\miniconda3\envs\xdagent\lib\site-packages\pydantic\json_schema.py", line 540, in new_handler_func
json_schema = js_modify_function(schema_or_field, current_handler)
File "d:\Envs\miniconda3\envs\xdagent\lib\site-packages\beanie\odm\fields.py", line 178, in __get_pydantic_json_schema__
json_schema = handler(schema)
File "d:\Envs\miniconda3\envs\xdagent\lib\site-packages\pydantic\_internal\_schema_generation_shared.py", line 38, in __call__
return self.handler(core_schema)
File "d:\Envs\miniconda3\envs\xdagent\lib\site-packages\pydantic\json_schema.py", line 493, in handler_func
json_schema = generate_for_schema_type(schema_or_field)
File "d:\Envs\miniconda3\envs\xdagent\lib\site-packages\pydantic\json_schema.py", line 1337, in json_or_python_schema
return self.generate_inner(schema['json_schema'])
File "d:\Envs\miniconda3\envs\xdagent\lib\site-packages\pydantic\json_schema.py", line 565, in generate_inner
json_schema = current_handler(schema)
File "d:\Envs\miniconda3\envs\xdagent\lib\site-packages\pydantic\_internal\_schema_generation_shared.py", line 38, in __call__
return self.handler(core_schema)
File "d:\Envs\miniconda3\envs\xdagent\lib\site-packages\pydantic\json_schema.py", line 493, in handler_func
json_schema = generate_for_schema_type(schema_or_field)
File "d:\Envs\miniconda3\envs\xdagent\lib\site-packages\pydantic\json_schema.py", line 1084, in function_plain_schema
return self.handle_invalid_for_json_schema(
File "d:\Envs\miniconda3\envs\xdagent\lib\site-packages\pydantic\json_schema.py", line 2273, in handle_invalid_for_json_schema
raise PydanticInvalidForJsonSchema(f'Cannot generate a JsonSchema for {error_info}')
pydantic.errors.PydanticInvalidForJsonSchema: Cannot generate a JsonSchema for core_schema.PlainValidatorFunctionSchema ({'type': 'with-info', 'function': <bound method PydanticObjectId.validate of <class 'beanie.odm.fields.PydanticObjectId'>>})
For further information visit https://errors.pydantic.dev/2.10/u/invalid-for-json-schema
问题原因
如下所示,在接口定义的时候指定了response_model 参数,用于告诉swagger当前接口的返回值的具体类型。但是由于指定的 Database 类使用了pydantic,属性中含有不支持的类型,但是没有做相应的序列化操作。
@router.get("/{rdb_id}", response_model=Database)
async def get_database_by_id(id: str):
解决方法
简单来说,只需要把 response_model 参数配置去调即可。
如果需要保留则可以把属性中pydantic不支持的类型,替换为支持的类型。
@router.get("/{rdb_id}")
async def get_database_by_id(id: str):