swagger $ref, Could not resolve reference: Tried to resolve a relative URL, without having a basePath. path: 'user.yaml' basePath: 'undefined'

Viewed 707

I changed $ref value several times,
but all of them reveal same error... help me plz
what's wrong?

swagger-ui error message
my directory image

swagger.js

import swaggereJsdoc from 'swagger-jsdoc';

const options = {
  swaggerDefinition: {
    info: {
      title: 'User API',
      version: '1.0.0',
      description: 'User API with express',
    },
    host: 'localhost:8000',
    // basePath: '/api',
  },
  apis: ['./routers/*.js', './swagger/*'],
};

export const specs = swaggereJsdoc(options);

user-router.js

/**
 * @swagger
 *  /api/users:
 *    get:
 *      tags:
 *      - user
 *      description: users (array)
 *      produces:
 *      - application/json
 *      responses:
 *       '200':
 *          description: success getUsers
 *
 *          schema:
 *            $ref: './swagger/user.yaml#/components/schemas/User'
 */

user.yaml

# /swagger/user.yml

components:
  schemas:
    User:
      properties:
        id:
          type: integer
          description: primary key

testing code before this question:

$ref: './swagger/user.yaml#/components/schemas/User'
$ref: '/swagger/user.yaml#/components/schemas/User'
$ref: 'swagger/user.yaml#/components/schemas/User'
$ref: './user.yaml#/components/schemas/User'
$ref: '/user.yaml#/components/schemas/User'
$ref: 'user.yaml#/components/schemas/User'
1 Answers

Here is a valid spec for your API. It may help you to identify whether your current implementation is suffering from syntax errors.

openapi: 3.0.0
  title: 'User API'
  version: '1.0.0'
  description: 'User API with express'

paths:
  /api/users:
    get:
      tags:
        - user
      description: users (array)
      responses:
        '200':
          $ref: '#/components/schemas/User'

components:
  schemas:  
    User:
      type: object
      properties:
        id:
          type: integer
          description: primary key

And this documentation on Base Paths for version 3.0.0 may be helpful https://swagger.io/docs/specification/api-host-and-base-path/. Also, if you haven't already, I would recommend installing the Swagger Viewer or OpenAPI extension on VSCode or an equivalent extension on whatever IDE you use to help you track down similar errors.

Related