【问题标题】:How to display a nested array example for a body parameter in Swagger UI?如何在 Swagger UI 中显示 body 参数的嵌套数组示例?
【发布时间】:2018-11-30 15:39:04
【问题描述】:

我的 POST 方法的主体中有一个嵌套数组作为参数:

 parameters:
 - in: body
   name: matrix
   description: blabla
   schema:
     type: array
     items:
       schema:
         type: array
         items:
           schema:
             type: double

我想添加一个示例,让这个数组在 Swagger UI 中可见。我尝试了以下方法,但它似乎不起作用 - 在 body 字段中没有显示任何示例。如果我在 Swagger UI 的正文字段中手动输入[[1.0, 2.0],[3.0, 4.0]],它就可以正常工作。

 parameters:
 - in: body
   name: matrix
   description: blabla
   schema:
     type: array
     items:
       schema:
         type: array
         items:
           schema:
             type: double
   example: [[1.0, 2.0],[3.0, 4.0]]

更新:执行 Helen 的建议后,它的外观如下:

【问题讨论】:

    标签: swagger swagger-ui swagger-2.0


    【解决方案1】:

    这是正确的版本:

      parameters:
        - in: body
          name: matrix
          description: blabla
          schema:
            type: array
            items:
              type: array
              items:
                type: number
                format: double
            example: [[1.0, 2.0],[3.0, 4.0]]
    

    修复列表:

    • schema 下不需要items
    • type: double 应该是 type: number + format: double(参见 Data Types)。
    • 数组example 应与架构中的type: array 并排。参数本身不支持example 关键字。

    您可以使用在线Swagger Editor 检查您的规范是否有语法错误,它会标记有错误的行。

    Swagger UI 2.x 的注意事项

    如果主体是基元数组,Swagger UI 2.x 不会显示主体参数示例。最新版本 Swagger UI 3.x 没有这个问题。

    2.x 的一种可能的解决方法是将 x-examples.default 键添加到 body 参数并指定示例值作为字符串

      parameters:
        - in: body
          name: matrix
          description: blabla
          schema:
            type: array
            items:
              type: array
              items:
                type: number
                format: double
            example: [[1.0, 2.0],[3.0, 4.0]]
          x-examples:
            default: '[[1.0, 2.0],[3.0, 4.0]]'  # <-----
    

    【讨论】:

    • 非常感谢您的解释性回答。现在可以正确识别数据类型。但是,该示例仍未显示。如果在招摇编辑器中输入,它可以工作。这可能是 Flasgger 中的错误吗?
    • @Damian 它在 Swagger UI 2.2.10 - i.stack.imgur.com/b6a8W.png 中对我来说很好用。你提到了 Flasgger——你如何在 Flasgger 中指定参数定义? Flasgger 使用哪个版本的 Swagger UI? (检查 swagger-ui.js 文件顶部的 cmets。)
    • swagger-ui.js 中的版本是 v.2.2.10。我直接在文档字符串(i.imgur.com/8m274Zl.png)中指定参数。您在屏幕截图中显示的不是响应变量吗?响应的示例也适用于我。这只是困扰我的参数
    • @Damian:谢谢,我现在明白了。顶部的示例是 response 示例,但没有 request 示例(正文示例)。我更新了答案以包含 2.x 的解决方法。
    • 太棒了。非常感谢
    猜你喜欢
    • 2022-10-04
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多