Cannot reference a component schema defined in a separate file in Swagger
Asked Answered
A

1

6

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?

Argil answered 17/6, 2019 at 13:22 Comment(4)
Does it work if you use $ref: './components.yaml##/components/schemas/AuthError'? Do you use Swagger UI or Swagger Editor?Lynnlynna
@Lynnlynna I changed it according to your suggestions, but it still gives me the same error. I am using Swagger UI via a node package of the same nameArgil
1) What version of Swagger UI? Can you post your Swagger UI config code? 2) Replace swagger: "3.0" with swagger: "2.0"Lynnlynna
@Lynnlynna my apologies, I'm using swagger UI express package. I edited the post aboveArgil
A
5

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'
Argil answered 17/6, 2019 at 14:14 Comment(1)
I doubted if this is a solution to the real problem. I have a similar scenario to yours and tried your suggestion as well, but it did not work. Honestly, I am still not sure if what I've done is correct or not.Baht

© 2022 - 2024 — McMap. All rights reserved.