【问题标题】:Split OpenApi Paths into multiple path definition files将 OpenApi 路径拆分为多个路径定义文件
【发布时间】:2020-08-04 01:02:27
【问题描述】:

我想更轻松地将我的路径(很多)拆分为它们自己的文件。

假设我有两条主要路径 /user 和 /anotherPath 以及几个子路径。现在我有一个 OpenApi 规范文件,它的路径被引用到一个索引文件,该文件包含对每个路径的引用。用它的参考定义每条路径,但写起来很笨拙。

我想要这样的东西:

openapi.json

{
...
  "paths": {
    "$ref": "paths/index.json"
  }
...
}

路径/index.json

{
  "/user": { // and everything that comes after user, e.g. /user/{userId}
    "$ref": "./user-path.json"
  },
  "/anotherPath": {  // and everything that comes after anotherPath, e.g. /anotherPath/{id}
    "$ref": "./anotherPath-path.json"
  }
}

路径/用户路径.json

{
  "/user": {
    "get": {...}
  },
  "/user/{userId}": {
    "get": {...}
  }
}

paths/anotherPath-path.json

{
  "/anotherPath": {
    "get": {...}
  },
  "/anotherPath/{id}": {
    "get": {...}
  }
}

这样,每当我向/user 或/anotherPath 添加另一个路径时,我都可以简单地编辑它们各自的路径文件,例如路径/用户路径.json。

EDIT1:显然,这个话题已经在讨论了。对于任何感兴趣的人:https://github.com/OAI/OpenAPI-Specification/issues/417。顺便说一句,我知道$ref 对paths 对象无效,但是一旦弄清楚如何正确拆分,这可能就不再需要了。

【问题讨论】:

标签: json swagger-2.0 openapi


【解决方案1】:

OpenAPI 没有子路径/嵌套路径的概念,每个路径都是一个单独的实体。 paths 关键字本身不支持$ref,只支持个别路径can be referenced。

鉴于您的 user-path.json 和 anotherPath-path.json 文件,引用路径定义的正确方法如下:

{
  ...
  "paths": {
    "/user": {
      "$ref": "paths/user-path.json#/~1user"  // ~1user is /user escaped according to JSON Pointer and JSON Reference rules
    },
    "/user/{id}": {
      "$ref": "paths/user-path.json#/~1user~1%7Bid%7D"  // ~1user~1%7Bid%7D is /user/{id} escaped 
    },
    "/anotherPath": {
      "$ref": "paths/anotherPath-path.json#/~1anotherPath"  // ~1anotherPath is /anotherPath escaped
    },
    "/anotherPath/{id}": {
      "$ref": "paths/anotherPath-path.json#/~1anotherPath~1%7Bid%7D"  // ~1anotherPath~1%7Bid%7D is /anotherPath/{id} escaped
    }
  }
  ...
}

YAML 版本:

paths:
  /user:
    $ref: "paths/user-path.json#/~1user"
  /user/{id}:
    $ref: "paths/user-path.json#/~1user~1%7Bid%7D"
  /anotherPath:
    $ref: "paths/anotherPath-path.json#/~1anotherPath"
  /anotherPath/{id}:
    $ref: "paths/anotherPath-path.json#/~1anotherPath~1%7Bid%7D"


如果您想在任意位置使用$ref(除了 OAS 允许 $refs 的地方),您必须使用可以解析任意 $refs 的解析器/工具预处理您的定义;这将为您提供一个有效的 OpenAPI 文件,该文件可与兼容 OpenAPI 的工具一起使用。一个这样的预处理工具是json-refs,你可以找到一个预处理的例子here。

【讨论】:

  • 这是我当前的设置,但我发现将确切路径写入 2 次是多余的:paths 中的 1 次和 user-path.json 中的 1 次。我想我将不得不等待paths 接受patternproperties 之类的东西
  • 或者,您可以在 paths 下直接使用带有 $ref 的示例,但使用 JSON $ref 解析器(不是 OpenAPI 解析器)将所有内容捆绑到一个文件中 - 请参阅更新的答案。
  • 其实,例如Swagger Previewer 可以很好地直接在 paths 中渲染 $ref。我正在使用 VS Code + Swagger Previewer 扩展,效果很好。不支持仅拆分 Path Item Objects 以便更轻松地与许多(子)路由一起使用。我将研究手动预处理,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-03
  • 2015-12-20
  • 1970-01-01
  • 2020-11-09
  • 2012-05-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多