无法加载外部 API 定义

Cannot load external API definition

我们正在使用 SwaggerEditor 编写 OAS3 API 规范。现在我们想转向更有条理的设置,我们将经常使用的通用定义(例如一些参数、错误、object 类型)移动到一些 共享文件以从其他 APIs.

OAS3 使用普通的 $ref 关键字支持这一点,例如:

$ref: "http://example.com/shared.yaml#/components/schemas/Person"

到目前为止我们尝试了什么

我设法在没有 CORS 错误的情况下启动 SwaggerEditor(这在谷歌搜索这个问题时似乎很常见,而且也首先发生在我们身上)。我可以在浏览器控制台验证:

但是外部参考仍然没有解决:编辑器实际上没有检查给定的定义(在上面的例子中Person) 存在 - 所以如果我引用一些虚假词,则不会显示任何错误。此外,右侧的交互式 Swagger UI 部分未正确显示链接类型......即它无法正常工作。

不是 CORS 问题

(一开始我们也运行遇到这个问题,但是现在按照下面的步骤解决了。)


1 这是editor.swagger.io显示的错误:

Errors

Fetch error
Failed to fetch http://127.0.0.1:8080/foo/bar.yaml

Fetch error
Possible cross-origin (CORS) issue? The URL origin (http://127.0.0.1:8080) does not match the page (http://editor.swagger.io). Check the server returns the correct 'Access-Control-Allow-*' headers.

2 尝试使用外部引用加载 API 时浏览器 JS 控制台显示的错误:

Access to fetch at 'http://127.0.0.1:8080/foo/bar.yaml' from origin 'http://editor.swagger.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我终于解决了我们的问题。我们似乎在调用 SwaggerEditor 时使用了错误的查询参数。

要正确加载(和解析)外部 YAML 规范,应使用查询参数 configUrl(而不是 url!)。例如:

http://127.0.0.1:8080/swagger-editor-master/?configUrl=http://127.0.0.1:8080/foo/bar.yaml

在哪里...

  • http://127.0.0.1:8080/swagger-editor-master/ 指向 Swagger 编辑器,并且
  • http://127.0.0.1:8080/foo/bar.yaml 指向我们要从我们当前在 Swagger 编辑器中编辑的任何内容中引用的规范文件。

像这样使用外部规范的引用,例如

$ref: "http://127.0.0.1:8080/foo/bar.yaml#/components/schemas/Payment"

将在右侧的 Swagger UI 中正确解析(例如,在 Schemas 部分中,引用的属性是可扩展的,等等)。但是,如果给出无效的外部引用,编辑器似乎不会抛出错误(相反,Swagger UI 只显示一个 'empty' 对象)。