【问题标题】:Cannot reference a component schema defined in a separate file in Swagger无法引用在 Swagger 的单独文件中定义的组件架构
【发布时间】:2019-06-17 13:22:58
【问题描述】:

我有以下 api 文档:

swagger: "3.0"
info:
  version: 0.0.1
  title: Test API
paths:
  /users:
    get:
      summary: Get all registered users
      produces:
      - application/json
      responses:
        200:
          description: Users successfully returned
        403:
          description: User not authorised to call this API
          schema:
            $ref: 'components.yaml#/components/schemas/AuthError'

AuthError 架构在名为 components.yaml 的单独 yaml 文件中定义:

components:
  schemas:
    AuthError:
      type: object
      properties:
        error:
          type: sting
          description: Error message

还有 Swagger 配置:

const swaggerDefinition = {
  info: {
    title: 'FlexiWAN REST API documentation',
    version: '1.0.0',
    description: 'This is the REST API for FlexiWAN management',
  },
  components: {},
  host: 'local.flexiwan.com:3443',
  basePath: '/api',
  securityDefinitions: {
    JWT: {
        type: 'apiKey',
        in: 'header',
        name: 'Authorization',
        description: "",
    }
  }

};
const options = {
  swaggerDefinition,
  apis: ['./swagger/**/*.yaml'],
};

const swaggerSpec = swaggerJSDoc(options);
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

但是当我尝试访问 Swagger UI 时出现以下错误:

paths./users.get.responses.403.schema.$ref 处的解析器错误 无法解析引用:尝试解析相对 URL,但没有 basePath。路径:'components.yaml' basePath:'未定义'

我在这里错过了什么?

【问题讨论】:

  • 使用$ref: './components.yaml##/components/schemas/AuthError'是否有效?你使用 Swagger UI 还是 Swagger Editor?
  • @Helen 我根据您的建议更改了它,但它仍然给我同样的错误。我正在通过同名节点包使用 Swagger UI
  • 1) 什么版本的 Swagger UI?你能发布你的 Swagger UI 配置代码吗? 2) 将swagger: "3.0" 替换为swagger: "2.0"
  • @Helen 抱歉,我正在使用 swagger UI express 包。我编辑了上面的帖子

标签: swagger openapi swagger-2.0 swagger-3.0


【解决方案1】:

所以我设法使用this great resource 解决了这个问题:

我所要做的就是在 API 文档文件的末尾添加对组件的引用,并相应地更改架构引用:

  403:
    description: User not authorised to call this API
    schema:
      $ref: '#components/schemas/AuthError'

components:
  $ref: './components.yaml'

【讨论】:

  • 我怀疑这是否能解决真正的问题。我有和你类似的情况,也尝试了你的建议,但没有奏效。老实说,我仍然不确定我所做的是否正确。
猜你喜欢
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
相关资源
最近更新 更多