Swagger/OpenAPI - 使用 $ref 传递可重用的定义参数

2023-11-26

假设我有一个像这样的参数limit。这个被到处使用,如果我需要更新它,则必须在各处更改它是一件痛苦的事情:

parameters:
    - name: limit
      in: query
      description: Limits the number of returned results
      required: false
      type: number
      format: int32

我可以使用 $ref 在其他地方定义它并使其可重用吗?我碰到这张票这表明有人想要更改或改进功能,但我无法判断它今天是否已经存在?


Swagger 2.0 中已经存在此功能。链接的票证讨论了它的一些特定机制,这不会影响此功能的功能。

在顶层对象(称为 Swagger 对象),有一个parameters您可以在其中定义可重用参数的属性。您可以为参数指定任何名称,并从路径/特定操作中引用它。顶级参数只是定义,不会自动应用于规范中的所有操作。

您可以在这里找到一个示例 -https://github.com/swagger-api/swagger-spec/blob/master/fixtures/v2.0/json/resources/reusableParameters.json- 即使有限制参数。

对于您的情况,您需要这样做:

# define a path with parameter reference
/path:
   get:
      parameters:
         - $ref: "#/parameters/limitParam"
         - $ref: "#/parameters/offsetParam"

# define reusable parameters:
parameters:
   limitParam:
      name: limit
      in: query
      description: Limits the number of returned results
      required: false
      type: integer
      format: int32
   offsetParam:
      name: offset
      in: query
      description: Offset from which start returned results
      required: false
      type: integer
      format: int32
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Swagger/OpenAPI - 使用 $ref 传递可重用的定义参数 的相关文章

随机推荐