How to use $ref in swagger file properly while working with swagger-ui-express and swagger-jsdoc How to use $ref in swagger file properly while working with swagger-ui-express and swagger-jsdoc express express

How to use $ref in swagger file properly while working with swagger-ui-express and swagger-jsdoc


Is there a way to work properly with $ref in swagger-ui-express?

Yes, there is, you have to resolve references in your YAML files by your self first, and provide result to Swagger UI then. You can do it with json-refs and yamljs libraries.

Here is the code snippet below shows you how you can do it:

const yamljs = require('yamljs');const { resolveRefs } = require('json-refs');/** * Return JSON with resolved references * @param {array | object} root - The structure to find JSON References within (Swagger spec) * @returns {Promise.<JSON>} */const multiFileSwagger = (root) => {  const options = {    filter: ["relative", "remote"],    loaderOptions: {      processContent: function (res, callback) {        callback(null, yamljs.parse(res.text));      },    },  };  return resolveRefs(root, options).then(    function (results) {      return results.resolved;    },    function (err) {      console.log(err.stack);    }  );};const swaggerDocument = await multiFileSwagger(  yamljs.load(path.resolve(__dirname, "./openapi/v1.yaml")));

You can also check the repo with full example how this solution works with swagger-ui-express: https://github.com/chuve/swagger-multi-file-spec


got the same problem here and find your question.

I've just solved mine so I guess I might help.

First, have you tried:

schema:      $ref: "schema.json"

without the . This is how they teach at the documentation.