Cannot reference a component schema defined in a separate file in Swagger

无人久伴 提交于 2020-01-24 15:05:28

问题


I have the following api documentation:

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'

Where the AuthError schema is defined in a separate yaml file called components.yaml:

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

And the Swagger configurations:

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));

But when I try to access Swagger UI I get the following error:

Resolver error at paths./users.get.responses.403.schema.$ref Could not resolve reference: Tried to resolve a relative URL, without having a basePath. path: 'components.yaml' basePath: 'undefined'

What am I missing here?


回答1:


So I managed to solve this using this great resource:

All I had to do is to add a reference to the components at the end of the API documentation file, and change the schema reference accordingly:

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

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


来源:https://stackoverflow.com/questions/56632260/cannot-reference-a-component-schema-defined-in-a-separate-file-in-swagger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!