OpenAPI 3.0嵌套数组查询参数校验失败问题求助
问题根源
当使用GET请求的Query参数传递二维数组时,你当前的OpenAPI配置(style: form + explode: true)会导致数组被扁平化序列化。Python requests 库会把二维数组 [[5,8,9],[1,4,7],[8,8,3]] 转成类似 elevationData=5&elevationData=8&elevationData=9&... 的格式,后端接收到的是一维的单个数值列表,而不是预期的嵌套数组结构,因此Schema校验时会判定第一个元素5不是数组类型,触发报错。
解决方案
推荐两种处理方式,优先选择更规范的POST方案:
方案一:改用POST请求传递JSON体(推荐)
GET请求的Query参数天生不适合传递复杂嵌套结构,改用POST请求将二维数组放在请求体中,能彻底避免序列化问题:
修改后的OpenAPI接口定义:
/astar/findLocalMaxiams: post: tags: - A Star Search summary: Finds Local Maximas by Elevation description: Returns an array of local maximas throughout the terrain using its corresponding elevations operationId: find_maximas requestBody: required: true content: application/json: schema: type: array items: type: array items: type: number responses: "200": description: Successful operation content: application/json: schema: type: array items: $ref: '#/components/schemas/Point' "400": description: Invalid elevation data format
对应的Python请求代码:
import requests arr = [[5, 8, 9], [1, 4, 7], [8, 8, 3]] response = requests.post('http://localhost:5000/astar/findLocalMaxiams', json=arr) print(response.content)
方案二:调整GET参数的序列化规则
如果必须使用GET请求,需要修改OpenAPI参数配置,并手动处理数组的序列化:
修改后的参数定义:
parameters: - name: elevationData in: query description: Elevation data required: true style: form explode: false allowReserved: true schema: type: array items: type: array items: type: number
对应的Python请求代码(需要将数组序列化为JSON字符串):
import requests import json arr = [[5, 8, 9], [1, 4, 7], [8, 8, 3]] params = {'elevationData': json.dumps(arr)} response = requests.get('http://localhost:5000/astar/findLocalMaxiams', params=params) print(response.content)
注意:后端需要额外将接收到的JSON字符串解析为二维数组。
内容的提问来源于stack exchange,提问作者ysingh-1636
相关产品推荐
相关产品推荐

