首页 文章

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

提问于
浏览
1

在这里招摇新手 . 我已经完成了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网页编辑器中遇到了验证问题 .

响应中的模式错误['response1'] . headers ['data'] . items不应该有其他propertiesadditionalProperty:$ ref response.response1.headers.data.items中的语义错误 . $ ref items $ refs不能匹配任何一个以下:“#/ definitions”,“#/ parameters”响应中的模式错误['response2'] . headers ['data'] . items不应该有其他属性additionalProperty:$ ref response.response2.headers.data中的语义错误.items . $ ref items $ refs不能匹配以下任何一项:“#/ definitions”,“#/ parameters”

看起来我正在错误地使用json引用,但我不确定为什么 .

我还尝试将response1和response2放在定义部分并直接引用它们(例如将$ ref直接指向'#/ definitions / response1'而不是'#/ responses / response1') . 但我从编辑器中得到一个错误,说我不能直接引用定义 .

构造这个定义的正确方法是什么?

1 回答

  • 1

    对身体的回应有 schema . 要引用模型定义,请使用 $ref reference作为 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标头,例如 X-RateLimitSet-Cookie ,而不是实际的主体负载 .

    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'
    

相关问题