Swagger 2.0:具有不同路径但请求和响应相同的多个 Path 对象

人气:1,049 发布:2022-09-11 标签: openapi swagger-2.0 swagger

问题描述

由于某些向后兼容的原因,我需要同时支持路径 /ab/a-b.

Due to some backward compatibility reasons, I need to support both the paths /ab and /a-b.

两个路径的请求和响应对象将是相同的.

The request and response objects are going to be the same for both of the paths.

我能否在我的 Swagger 规范中包含类似以下内容,这样我就不必为两个路径重复请求和响应对象定义.

Can I have something like the following in my Swagger spec so that I do not have to repeat the request and response object definitions for both the paths.

paths:
  /ab:
  /a-b:
    post:
    ...

推荐答案

是的,你可以有一个引用另一个路径项的路径项:

Yes, you can have a path item that references another path item:

paths:
  /ab:
    post:
      summary: ...
      ...
      responses:
        ...

  /a-b:
    $ref: '#/paths/~1ab'   # <------------

这里,~1ab/ab 的编码版本(见下文).

Here, ~1ab is an encoded version of /ab (see below).

此方法的一个限制是您不能在引用的路径项的所有操作中都有 operationId.这是因为路径的副本最终具有相同的 operationId 值,但 operationId 必须是唯一的.

One limitation of this approach is that you cannot have operationId in all operations of the referenced path item. This is because the copy of the path ends up with the same operationId values, but operationId must be unique.

如果字符 ~/ 出现在节点名称中(如路径名称的情况,例如 /ab),它们必须是编码:~~0/~1:

If the characters ~ and / are present in node names (as in case of path names, e.g. /ab) they must be encoded: ~ as ~0, and / as ~1:

/ab~1ab$ref: '#/paths/~1ab'/foo/bar~1foo~1bar$ref: '#/paths/~1foo~1bar'/ab~cd~1ab~0cd#/paths/~1ab~0cd /ab~1ab$ref: '#/paths/~1ab' /foo/bar~1foo~1bar$ref: '#/paths/~1foo~1bar' /ab~cd~1ab~0cd#/paths/~1ab~0cd

此外,{ } 和 URI 片段标识符中不允许使用的其他字符 (RFC 3986, section 3.5) 需要进行百分比编码.例如,{ 变为 %7B} 变为 %7D.

Additionally, { } and other characters not allowed in URI fragment identifiers (RFC 3986, section 3.5) need to be percent-encoded. For example, { becomes %7B, and } becomes %7D.

/{zzz}~1{zzz} (/替换为~1)→ ~1%7Bzzz%7D(百分比编码)→ $ref: '#/paths/~1%7Bzzz%7D'/foo/{zzz}~1foo~1{zzz} (/替换为~1)→ ~1foo~1%7Bzzz%7D(百分比编码)→ $ref: '#/paths/~1foo~1%7Bzzz%7D' /{zzz}~1{zzz} ( / replaced with ~1) → ~1%7Bzzz%7D (percent-encoded) → $ref: '#/paths/~1%7Bzzz%7D' /foo/{zzz}~1foo~1{zzz} ( / replaced with ~1) → ~1foo~1%7Bzzz%7D (percent-encoded) → $ref: '#/paths/~1foo~1%7Bzzz%7D'

请注意,您只需要对路径名进行编码,而不是 #/paths/ 前缀.

Note that you need to encode just the path name and not the #/paths/ prefix.

783