Swagger/OpenAPI - 使用 $ref 传递可重用的定义参数 [英] Swagger/OpenAPI - use $ref to pass a reusable defined parameter
问题描述
假设我有一个像 limit
这样的参数.这个到处都在使用,如果我需要更新它,就不得不到处更改它是一件痛苦的事:
Let's say I've got a parameter like limit
. This one gets used all over the place and it's a pain to have to change it everywhere if I need to update it:
parameters:
- name: limit
in: query
description: Limits the number of returned results
required: false
type: number
format: int32
我可以使用 $ref 在别处定义它并使其可重用吗?我遇到 这张票 这表明有人想要更改或改进功能,但我不知道它今天是否已经存在?
Can I use $ref to define this elsewhere and make it reusable? I came across this ticket which suggests that someone wants to change or improve feature, but I can't tell if it already exists today or not?
推荐答案
这个功能在 Swagger 2.0 中已经存在.链接的票证讨论了它的一些特定机制,这些机制不会影响此功能的功能.
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.
在顶级对象(称为 Swagger 对象)中,有一个 parameters
属性,您可以在其中定义可重用的参数.您可以给参数起任何名称,并从路径/特定操作中引用它.顶级参数只是定义,不会自动应用于规范中的所有操作.
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.
你可以在这里找到一个例子 - https://github.com/swagger-api/swagger-spec/blob/master/fixtures/v2.0/json/resources/reusableParameters.json - 即使有限制参数.
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
这篇关于Swagger/OpenAPI - 使用 $ref 传递可重用的定义参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!