【问题标题】:How to refer to an external JSON file containing response examples in Swagger?如何在 Swagger 中引用包含响应示例的外部 JSON 文件?
【发布时间】:2017-05-14 14:55:16
【问题描述】:

在我的 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

【问题讨论】:

    标签: swagger openapi swagger-2.0


    【解决方案1】:

    你可以用wrapComponents做到这一点

    示例openapi.yaml

    openapi: 3.0.1
    info:
      title: Swagger Petstore
      description: 'This is a sample server Petstore server'
      version: 1.0.0
    servers:
    - url: https://petstore.swagger.io/v2
    - url: http://petstore.swagger.io/v2
    paths:
      /router/rest:
        get:
          summary: test
          operationId: test
          responses:
            '200':
              content:
                application/json:
                  schema:
                    type: object
                  examples:
                    success:
                      summary: JSON example
                      value: Loading...
                      externalValue: 'example/test.json'
                application/xml:
                  schema:
                    type: object
                    xml:
                      name: xml
                  examples:
                    success:
                      summary: XML example
                      value: Loading...
                      externalValue: 'example/test.xml'
    

    将自定义插件添加到index.html

    // Examples map
    const examples = {};
    
    // Custom plugin for the logic that happens before the response element is created
    const CustomPlugin = () => {
      return {
        wrapComponents: {
          response: (Original, { React, oas3Actions, oas3Selectors }) => (props) => {
            const contentType = oas3Selectors.responseContentType(props.path, props.method)
            const externalValue = props.response.getIn(['content', contentType, 'examples', props.activeExamplesKey, 'externalValue'])
            // Check if externalValue field exists
            if (externalValue) {
              // Check if examples map already contains externalValue key
              if (examples[externalValue]) {
                // Set example value directly from examples map
                props.response = props.response.setIn(['content', contentType, 'examples', props.activeExamplesKey, 'value'], examples[externalValue])
              } else {
                // Download external file
                fetch(externalValue)
                .then(res => res.text())
                .then(data => {
                  // Put downloaded file content into the examples map
                  examples[externalValue] = data
                  // Simulate select another example action
                  oas3Actions.setActiveExamplesMember({
                    "name": 'fake',
                    "pathMethod": [props.path, props.method],
                    "contextType": "responses",
                    "contextName": props.code
                  })
                  // Reselect this example
                  oas3Actions.setActiveExamplesMember({
                    "name": props.activeExamplesKey,
                    "pathMethod": [props.path, props.method],
                    "contextType": "responses",
                    "contextName": props.code
                  })
                })
                .catch(e => console.error(e))
              }
            }
            return React.createElement(Original, props)
          }
        }
      }
    }
    
    window.onload = function() {
      const ui = SwaggerUIBundle({
        url: 'openapi.yaml',
        dom_id: '#swagger-ui',
        deepLinking: true,
        presets: [
          SwaggerUIBundle.presets.apis,
          SwaggerUIStandalonePreset
        ],
        plugins: [
          SwaggerUIBundle.plugins.DownloadUrl,
          // Add custom plugin
          CustomPlugin
        ],
        layout: "StandaloneLayout"
      });
    
      window.ui = ui;
    };
    

    【讨论】:

      【解决方案2】:

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

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

      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 定义文件的位置解析的。

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

      【讨论】:

        猜你喜欢
        • 2018-05-18
        • 1970-01-01
        • 2021-01-20
        • 1970-01-01
        • 2011-05-10
        • 2016-01-25
        • 1970-01-01
        • 1970-01-01
        • 2022-08-16
        相关资源
        最近更新 更多