openAPI 无法解析对外部文件的引用。组件名称包含无效字符

tba*_*tch 3 json yaml openapi openapi-generator

我试图将一个大的 yml 分成一堆较小的 yml 文档。我按照David Garcia 提供的示例进行操作,然后使用 OpenAPI CodeGenerator 生成我的模型。OpenAPI Generator 抱怨[BUG] attribute components.schemas.Schema name doesn't adhere to regular expression ^[a-zA-Z0-9.-_]+$. 因此,我尝试通过克隆 David Garcia 的存储库并在本地部署来使用 David Garcia 的示例,但我遇到了相同的错误。我决定在swagger editor中检查它,我遇到了同样的问题,但错误消息显示

Semantic error at components.schemas.$ref
Component names can only contain the characters A-Z a-z 0-9 - . _
Jump to line 25
Run Code Online (Sandbox Code Playgroud)

我正在使用 David Garcia 示例中的 yaml:

Semantic error at components.schemas.$ref
Component names can only contain the characters A-Z a-z 0-9 - . _
Jump to line 25
Run Code Online (Sandbox Code Playgroud)

您可以轻松地将其粘贴到编辑器中并亲自查看错误。OpenAPI 规范规定组件对象可以是对象或引用Map[string, Schema Object | Reference Object]模式对象定义说:“或者,任何时候可以使用模式对象时,都可以使用引用对象来代替它。”

我知道我可以将其放在 yaml 文档中,如下所示:

openapi: "3.0.0"
info:
  version: 1.0.0
  title: Swagger Petstore
  description: Multi-file boilerplate for OpenAPI Specification.
  license:
    name: MIT
  contact:
    name: API Support
    url: http://www.example.com/support
    email: support@example.com
servers:
  - url: http://petstore.swagger.io/v1
tags:
  - name: pets
paths:
  /pets:
    $ref: "./resources/pets.yaml"
  /pets/{petId}:
    $ref: "./resources/pet.yaml"
components:
  parameters:
    $ref: "./parameters/_index.yaml"
  schemas:
    $ref: "./schemas/_index.yaml"
  responses:
    $ref: "./_index.yaml"
Run Code Online (Sandbox Code Playgroud)

但为什么我不能引用外部索引呢?在线示例说是,开放 API 规范说是,但我无法让它工作。

Hel*_*len 6

OpenAPI 规范允许$ref 任何地方使用,这是一个常见的误解。实际上,$ref仅在 OpenAPI 规范规定字段值可以是“引用对象”或“架构对象”的地方才允许使用。

具体来说,此代码片段不是有效的 OpenAPI 语法:

components:
  parameters:
    $ref: "./parameters/_index.yaml"
  schemas:
    $ref: "./schemas/_index.yaml"
  responses:
    $ref: "./_index.yaml"
Run Code Online (Sandbox Code Playgroud)

Map[string, Schema Object | Reference Object]意味着components.schemas节点必须是一个映射,其中键是模式名称,值是内联模式或模式引用。正如第二个示例(这是有效的 OpenAPI 语法):

components:
  parameters:
    $ref: "./parameters/_index.yaml"
  schemas:
    $ref: "./schemas/_index.yaml"
  responses:
    $ref: "./_index.yaml"
Run Code Online (Sandbox Code Playgroud)

某些实现用于在任何地方处理 $refs 的解决方法是使用通用 JSON $ref 解析器(例如json-refs )预处理规范来解析那些非标准 $refs。例如,您引用此示例的博客文章swagger-cli用于解析非标准 $refs 并创建单个合并文件。