首页 > 解决方案 > 将 OpenApi 路径拆分为多个路径定义文件

问题描述

我想更容易地将我的路径(很多)拆分为他们自己的文件。

假设我有两条主要路径/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": {...}
  }
}

路径/anotherPath-path.json

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

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

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

标签: jsonswagger-2.0openapi

解决方案


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

给定您的user-path.jsonanotherPath-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 ,你可以在这里找到一个预处理的例子。


推荐阅读