使用Connexion 2.14.0+Flask基于OpenAPI3.0校验Payload失效求助
问题解决方案
1. 修复OpenAPI规范的语法错误
你的OpenAPI Schema中accountIds字段的items定义不完整,OpenAPI 3.0要求数组类型必须明确指定items的Schema,缺失该定义会导致校验器无法正确解析Schema规则,进而跳过部分校验逻辑。
修正后的CalculationRequest Schema:
components: schemas: CalculationRequest: type: object additionalProperties: false required: - accountGroupId - accountIds properties: accountGroupId: type: string accountIds: type: array items: type: string # 根据实际需求替换为integer等类型
2. 显式启用请求体校验
虽然Connexion默认启用请求体校验,但显式指定validate_requests=True可以确保校验逻辑生效,避免配置被意外覆盖:
application.add_api( 'api_specification.yaml', strict_validation=True, validate_requests=True )
3. 确保请求Content-Type匹配
你的OpenAPI中指定的请求Content-Type是application/json; charset=utf-8,请确保请求头的Content-Type与之匹配(可简化为application/json)。如果Content-Type不匹配,Connexion会跳过Schema校验,直接将请求传递给处理函数。
4. 验证Connexion与jsonschema版本兼容性
Connexion 2.14.0依赖特定版本的jsonschema,若版本不兼容可能导致additionalProperties校验失效。可以尝试锁定jsonschema版本为3.2.0(Connexion 2.x推荐的稳定版本),执行:
pip install jsonschema==3.2.0
5. 测试校验逻辑
发送如下测试请求验证:
{ "account_group_id": "test-group", "account_ids": ["test-id-1"] }
此时应该返回400错误,提示存在额外属性account_group_id和account_ids。
内容的提问来源于stack exchange,提问作者Andrei Kitaitsev
相关产品推荐
相关产品推荐

