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

比方说,我有一个像limit的参数。 这个被广泛使用,如果需要更新的话,在任何地方改变它都是一件痛苦的事情:

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

我可以使用$ ref来定义这个地方,并使其可重用? 我遇到这张票 ,这表明有人想改变或改善function,但我不知道它是否已经存在或没有?

Swagger 2.0中已经存在此function。 链接的故障单谈论它的一些具体机制,不影响此function的function。

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

你可以在这里find一个例子 – 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" # define reusable parameters: parameters: limitParam: name: limit in: query description: Limits the number of returned results required: false type: number format: int32