隐藏所有其他属性的 Swagger 示例属性

Swagger example attribute hiding all other attributes

我正在 swaggerhub 上写 Swagger 定义。可以选择在多个 Swagger 之间共享模型。 swagger 完成后,可以选择下载已导入 linked 定义的已解析 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

现在,如果我在编辑器中导入此更改,则只缺少属性 ex1ex2 以及实际属性 a1a2

当我们有继承时问题会加剧。

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

这是一个示例 wi

现在让我们在C中引入example属性。在任何级别添加 example 属性后,将忽略所有其他属性。

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

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

这就是 example 的工作原理。引用 OpenAPI 2.0 Specification:

A free-form ... example of an instance for this schema.

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

中的属性


在您使用 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

这又是为什么 C 中的架构级别 example 会覆盖其他所有内容。


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

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