Swagger/OpenAPI-使用$ ref传递可重用的已定义参数 [英] Swagger/OpenAPI - use $ref to pass a reusable defined parameter

查看:1084
本文介绍了Swagger/OpenAPI-使用$ ref传递可重用的已定义参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个像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.

您可以在此处找到示例-

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.

您要这样做:

# 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆