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

假设我有一个类似 limit的参数。如果我需要更新它的话,到处都可以使用它,而且到处都要更改它是一件很痛苦的事情:

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

我是否可以在其他地方使用 $ref 来定义它并使其可重用?我遇到了 这张票,它表明有人想改变或改进功能,但我不能告诉它是否已经存在今天还是没有?

55703 次浏览

This feature already exists in Swagger 2.0. The linked ticket talks about some specific mechanics of it which doesn't affect the functionality of this feature.

At the top level object (referred to as the Swagger Object), there's a parameters property where you can define reusable parameters. You can give the parameter any name, and refer to it from paths/specific operations. The top level parameters are just definitions and are not applied to all operations in the spec automatically.

You can find an example for it here - https://github.com/swagger-api/swagger-spec/blob/master/fixtures/v2.0/json/resources/reusableParameters.json - even with a limit parameter.

In your case, you'd want to do this:

# 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

For completeness, here's how it would look like in OpenAPI (a.k.a swagger v3):

openapi: "3.0.0"
servers:
- url: /v1
description: local server


paths:
/path:
get:
parameters:
- $ref: "#/components/parameters/limitParam"


components:
parameters:
limitParam:
name: limit
in: query
description: Limits the number of returned results
required: false
schema:
type: integer
minimum: 10
default: 10
multipleOf: 10 # matches 10, 20, ...
format: int32