如何在 Swagger 中引用包含响应示例的外部 JSON 文件? [英] How to refer to an external JSON file containing response examples in Swagger?

查看:386
本文介绍了如何在 Swagger 中引用包含响应示例的外部 JSON 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my Swagger spec file, I want to return example responses, for that I can add examples in response. But that makes my spec file quite big and error prone. Is there a way to refer to a file containing JSON of an example object?

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

I tried something like below but it doesn't seem to work.

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

推荐答案

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

The example keyword does not support $ref, and OpenAPI 2.0 does not have a way to reference external examples.

您需要 OpenAPI 3.0 (openapi: 3.0.0) 才能引用外部示例.OAS3 提供了用于此目的的 externalValue 关键字:

You need OpenAPI 3.0 (openapi: 3.0.0) to be able to reference external examples. OAS3 provides the externalValue keyword for this purpose:

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'

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

externalValue can be an absolute or relative URL. Note that relative externalValue URLs are resolved against the API server URL (servers[*].url) and not the location of the API definition file.

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

Note for Swagger UI and Swagger Editor users: Currently (as of December 2019) the content of externalValue examples is not displayed. Follow this issue for updates.

这篇关于如何在 Swagger 中引用包含响应示例的外部 JSON 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆