Swagger 语法:如何从可重用响应中引用模型定义

Swagger Syntax: How to reference a model definition from a reusable response

新手在这里大摇大摆。我已经完成了 swagger primer,据我所知,我下面的示例应该有效。

我的响应类型只是不同结构的数组(这些结构在全局定义部分中定义以减少膨胀,因为它们可以嵌套,因此可以重复使用)。

这是我的定义:

consumes:
  - application/json
produces:
  - application/json
schemes:
  - http
swagger: '2.0'
[...Additional details excluded...]

paths:
  /first:
    get:
      responses:
        '200':
          $ref: '#/responses/response1'
  /second:
    get:
      responses:
        '200':
          $ref: '#/responses/response2'


definitions:
  ObjectA:
    type: object
    properties:
      listOfObjBs:
        type: array
        items:
          $ref: '#/definitions/ObjectB'
  ObjectB:
    type: object
    properties:
      listOfObjCs:
        type: array
        items:
          $ref: '#/definitions/ObjectC'
  ObjectC:
    description: A build
    type: object
    properties:
      someNumericData:
        type: integer
        format: int64

responses:
  response1:
    description: There are 2 types of responses, this is the first kind.
    schema:
      type: object
    headers:
      data: 
        type: array
        items:
          $ref: '#/definitions/ObjectA'
  response2:
    description: This is the second kind.
    schema:
      type: object
    headers:
      data:
        type: array
        items:
          $ref: '#/definitions/ObjectC'

但是,我 运行 陷入 swagger 网络编辑器中的验证问题。

Schema error at responses['response1'].headers['data'].items should NOT have additional propertiesadditionalProperty: $ref

Semantic error at responses.response1.headers.data.items.$ref items $refs cannot match any of the following: "#/definitions", "#/parameters"

Schema error at responses['response2'].headers['data'].items should NOT have additional properties additionalProperty: $ref

Semantic error at responses.response2.headers.data.items.$ref items $refs cannot match any of the following: "#/definitions", "#/parameters"

我似乎错误地使用了 json 引用,但我不确定为什么。

我也试过将 response1 和 response2 放在定义部分并直接引用它们(例如,将路径下的 $ref 直接指向 '#/definitions/response1' 而不是 '#/responses/response1' ).但是我从编辑那里得到一个错误,说我不能直接引用定义。

构建此定义的正确方法是什么?

body 的回复有 schema。要引用模型定义,请使用 $ref 引用作为 schema:

的值
responses:
  response1:  # <--- This node is on the same level as the status codes '200'/'404' etc.
    description: There are 2 types of responses, this is the first kind.
    schema:
      $ref: '#/definitions/ObjectA'

      # Or if the response is an array:
      # type: array
      # items:
      #   $ref: '#/definitions/ObjectA'


  response2:
    description: This is the second kind.
    schema:
      $ref: '#/definitions/ObjectC'

您的示例中的错误是将引用放在 headers 下。 headers 部分定义了响应的 HTTP headers,例如 X-RateLimitSet-Cookie,而不是实际的 body 负载。

  response1:
    description: There are 2 types of responses, this is the first kind.
    schema:
      type: object

    # Errors were caused by this
    headers:
      data: 
        type: array
        items:
          $ref: '#/definitions/ObjectA'