You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

openapi_core validate_request错误描述模糊,如何获取精确错误信息?

问题:OpenAPI请求体验证仅返回模糊错误,如何获取详细信息?

使用openapi_core 0.18.1的validate_request方法验证请求数据与OpenAPI Schema:

from openapi_core import validate_request
validate_request(request_data, self.spec)

对应的请求体Schema片段:

getRequest:
  type: object
  properties:
    type_of:
      type: string
    name:
      type: string

请求代码:

r = requests.post(url='host/something/v012/get', data={'type_of': 'user', 'name': 'test'})

验证时仅抛出模糊错误:

E                   Request body validation error

无法定位具体不符点,如何获取精确错误详情?


解决方法

1. 捕获验证异常并提取详细错误信息

openapi_core抛出的RequestValidationError包含errors属性,存储了所有具体的验证失败细节。修改代码捕获异常并遍历输出:

from openapi_core import validate_request
from openapi_core.exceptions import RequestValidationError

try:
    validate_request(request_data, self.spec)
except RequestValidationError as e:
    # 遍历所有错误并打印详情
    for err in e.errors:
        print(f"错误位置: {err.location}")
        print(f"错误信息: {err.message}")
        print(f"错误类型: {err.__class__.__name__}")

这会输出每个错误的具体位置(比如请求体的某个字段)、错误原因(比如格式不符、缺少字段等),帮助快速定位问题。

2. 检查请求数据的传输格式

你的请求用了requests.post的data参数,这会把数据以application/x-www-form-urlencoded(表单)格式发送,但你的Schema定义的是JSON对象类型的请求体,openapi_core会按OpenAPI规范中声明的Content-Type(通常是application/json)解析请求体,导致表单格式的数据无法被正确解析为JSON对象,从而触发验证错误。

修改请求代码,改用json参数发送JSON格式数据:

r = requests.post(url='host/something/v012/get', json={'type_of': 'user', 'name': 'test'})

这样请求会自动设置Content-Type: application/json,openapi_core就能正确解析请求体并进行验证。


内容的提问来源于stack exchange,提问作者MG9901

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 06:23:13