如何在 Swagger 中引用包含响应示例的外部 JSON 文件?

zod*_*i91 5 swagger swagger-2.0 openapi

在我的 Swagger 规范文件中,我想返回示例响应,因为我可以examples在响应中添加它。但这使得我的规范文件相当大并且容易出错。有没有办法引用包含示例对象的 JSON 的文件?

我尝试了类似下面的方法,但似乎不起作用。

get:
  tags:
    - businesses
  summary: Get Taxable Entities details 
  description: ''
  operationId: getTaxableEntities
  produces:
    - application/json
  parameters:
    - name: business_id
      in: path
      required: true
      type: integer
      format: int32
    - name: gstIn
      in: query
      required: false
      type: integer
      format: int32
  responses:
    '200':
      description: Taxable Entities
      schema:
        type: file
        default:
          $ref: taxable_entity_example.json
    '401':
      description: You are not authorised to view this Taxable Entity
Run Code Online (Sandbox Code Playgroud)

Hel*_*len 4

example关键字不支持$ref,并且 OpenAPI 2.0 没有办法引用外部示例。

您需要OpenAPI 3.0 ( openapi: 3.0.0) 才能引用外部示例。OAS3externalValue为此提供了关键字:

openapi: 3.0.2
...

      responses:
        '200':
          description: Taxable Entities
          content:
            application/json:
              schema:
                type: object
              examples:
                myExample:  # arbitrary name/label
                  externalValue: 'https://myserver.com/examples/taxable_entity_example.json'
Run Code Online (Sandbox Code Playgroud)

externalValue可以是绝对或相对 URL。请注意,相对externalValueURL 是根据 API 服务器 URL ( servers[*].url) 解析的,而不是根据 API 定义文件的位置解析的。

Swagger UI 和 Swagger Editor 用户请注意:目前(截至 2019 年 12 月)externalValue示例内容未显示。请关注此问题以获取更新。