Swagger OpenAPI路径变量style simple+object类型校验报错求助
场景复现
使用版本2.22.0的swagger-request-validator,配置如下OpenAPI 3.0 YAML:
info: title: Sample API version: 1.0.0 openapi: 3.0.0 paths: /demo/{groupIdentifier}: get: description: This API which will provide all the members of a group. operationId: get-group-v2 responses: "200": description: Successful response parameters: - description: Composite group identifier explode: false in: path name: groupIdentifier required: true allowReserved: true schema: properties: domainCode: description: Code of the master data domain type: string groupTypeCode: description: The prototype type of the group that has to be searched type: string type: object style: simple
按照OpenAPI规范中style: simple+explode: false的要求,以逗号分隔的键值对格式传递路径参数,示例请求URL:http://test.com/demo/domainCode,CUSTOMER,groupTypeCode,CUSTOMER_GROUP
运行时触发如下错误:
"oas://openapi.yaml": failed with reason: "[ERROR - Unable to parse JSON - Unrecognized token 'domainCode': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false') at [Source: (String)"domainCode,CUSTOMER,groupTypeCode,CUSTOMER_GROUP"; line: 1, column: 11].: []]"
调试发现,swagger-request-validator正尝试将逗号分隔的参数值解析为JSON,从而引发解析失败。
问题根源
swagger-request-validator 2.22.0版本对OpenAPI 3.0中路径对象参数的style和explode配置支持不完善。该版本默认会将路径中的对象类型参数当作JSON字符串解析,忽略了style: simple指定的键值对序列化规则,导致与预期的参数传递格式不兼容。
解决方案
改用JSON字符串传递参数
将路径参数值改为JSON格式的字符串(注意URL编码),示例URL:http://test.com/demo/%7B%22domainCode%22%3A%22CUSTOMER%22%2C%22groupTypeCode%22%3A%22CUSTOMER_GROUP%22%7D
这种方式匹配库默认的JSON解析逻辑,可直接通过验证。升级swagger-request-validator版本
该问题在后续版本(如3.x及以上)中已修复,新版本对OpenAPI 3.0的参数序列化规则支持更全面,能正确识别style: simple和explode: false配置,解析逗号分隔的键值对格式参数。自定义参数解析逻辑(无法升级时)
在验证前拦截路径参数,手动按照simple风格+explode=false的规则将逗号分隔的字符串解析为对象,再传递给swagger-request-validator进行验证。
内容的提问来源于stack exchange,提问作者Shikha Shah

