首页 > 解决方案 > 隐藏所有其他属性的 Swagger 示例属性

问题描述

我正在swaggerhubSwagger上写一个定义。可以选择在多个 Swagger 之间共享模型。swaggers 完成后,可以选择下载已解析的 Swagger 并导入链接的定义。

我的问题是,这个已解决的下载会example在模型中添加一个节点,当我们再次在编辑器中复制这个新的 Swagger 时,无论出于何种原因,该节点都会覆盖每个属性。

假设我们有以下样本

---
swagger: "2.0"
info:
  description: ""
  version: 1.0.0
  title: title
host: "example.com"
basePath: /
schemes:
- http
consumes:
- application/json
produces:
- application/json
paths:
  /test-service:
    post:
      tags:
      - test-service
      operationId: test-service
      parameters:
      - in: body
        name: body
        description: body
        required: true
        schema:
          $ref: '#/definitions/A'
      responses:
        201:
          description: success
          schema:
            $ref: '#/definitions/A'
definitions:
  A:
    type: object
    properties:
      a1:
        type: string
      a2:
        type: string

以下是它在Swagger UI,

这是正确的方法,但是当我在模型中有一个示例节点时A,UI中只显示示例属性,

正确显示

这是我所指的变化

  A:
    type: object
    properties:
      a1:
        type: string
      a2:
        type: string
    example:
      ex1: Hello
      ex2: World

现在,如果我在编辑器中导入此更改,则仅缺少属性和实际ex1属性ex2a1a2

显示不正确

当我们拥有继承权时,问题会更加严重。

发生的情况是层次结构中的最低节点具有example仅在 UI 中显示的属性中列出的属性,而不是显示所有属性

这是一个示例 wi正确显示

现在让我们exampleC. 在任何级别添加example属性后,所有其他属性都将被忽略。

这是example属性文档的链接https://swagger.io/docs/specification/2-0/adding-examples/

没有描述这种奇怪的行为。

显示不正确

标签: swaggerswagger-uiswagger-2.0

解决方案


就是这样example工作的。引用OpenAPI 2.0 规范

一个自由形式的......这个模式的一个实例的例子。

也就是说,是整个架构example的示例。这就是模式级别按原样显示的原因。它会覆盖任何属性级别的示例,并且不会自动包含未包含在.exampleexample


在你的最后一个例子中allOf,架构A等同于

definitions:
  A:
    type: object
    properties:
      a1:
        type: string
      a2:
        type: string
      b1:
        type: string
      b2:
        type: string
      c1:
        type: string
      c2:
        type: string
    example:
      ex1: Hello
      ex2: world

这也是为什么架构级别example覆盖C其他所有内容的原因。


您可能想改用属性级示例:

definitions:
  A:
    type: object
    properties:
      a1:
        type: string
        example: Hello   # <---
      a2:
        type: string
        example: world   # <---

推荐阅读