首页 > 解决方案 > Python中的Swagger数组响应不适用于生成的客户端

问题描述

我正在使用带有 Flask 和 connexion 的 Swagger 在 Python 中实现 REST API。我在 Python 中使用 swagger-codegen 生成了一个客户端。当使用带有返回数组的 GET 调用的接口时,我可以在调试日志中看到响应按预期到达客户端,但客户端没有正确处理它。

这是我的招摇 yaml 定义

schemes:
 - http
paths:             
  /elements: 
      get:
        summary: 'Fetch elements from the database'
        operationId: elements.get_elements
        responses:
          '200':
              description: Fetch elements from the database
              schema:
                 type: array
                 items:
                 $ref: '#/definitions/element'   


definitions:
  element:
    type: object
    properties:
      id:           { type: string }
      desc:         { type: string }

这是我的 API 的实现

from flask import jsonify

elements = [{'id':'1', 'desc':'description1'},{'id':'2', 'desc':'description2'}]


def get_elements():
    """
        Gets elements
    """
    return jsonify(elements)

这是我的客户通话记录

>>> api_instance.elements_get_elements()
2019-11-26 11:28:02,946 DEBUG Starting new HTTP connection (1): localhost:5123
2019-11-26 11:28:02,946 DEBUG Starting new HTTP connection (1): localhost:5123
send: b'GET /elements HTTP/1.1\r\nHost: localhost:5123\r\nAccept-Encoding: identity\r\nUser-Agent: Swagger-Codegen/1.0.0/python\r\nContent-Type: application/json\r\n\r\n'
reply: 'HTTP/1.0 200 OK\r\n'
header: Content-Type: application/json
header: Content-Length: 108
header: Server: Werkzeug/0.16.0 Python/3.6.8
header: Date: Tue, 26 Nov 2019 10:28:02 GMT
2019-11-26 11:28:02,953 DEBUG http://localhost:5123 "GET /elements HTTP/1.1" 200 108
2019-11-26 11:28:02,953 DEBUG http://localhost:5123 "GET /elements HTTP/1.1" 200 108
2019-11-26 11:28:02,954 DEBUG response body: [
  {
    "desc": "description1", 
    "id": "1"
  }, 
  {
    "desc": "description2", 
    "id": "2"
  }
]

2019-11-26 11:28:02,954 DEBUG response body: [
  {
    "desc": "description1", 
    "id": "1"
  }, 
  {
    "desc": "description2", 
    "id": "2"
  }
]

{'desc': None, 'id': None}

如您所见,最后一行显示的结果不是我对响应数组的预期解释

标签: pythonswaggerswagger-codegen

解决方案


推荐阅读