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

瘦欲@ 提交于 2020-01-24 06:01:11

问题


I started to use swagger with swagger-ui-express and swagger-jsdoc to auto document my existing API, which is written with nodejs and express (like described here - example).

I came across a problem when I tried to add a $ref to an existing JSON Schema file (that sits inside my project on the same directory as all my js files) on my annotation.

My directory looks like this

I tried to write the local path (./schema.json) and the absolute path, tried to use #, using many syntaxes and nothing worked.

My annotation looks like this:

/**
 * @swagger
 * /testing:
 *    get:
 *      description: This should show the json schema
 *      responses:
 *          200:
 *              description: "successful operation"
 *              schema:
 *                 $ref: "./schema.json"
 */

I expected the swagger ui to show me the JSON schema in my request section by. I get the following error -

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

I looked the problem up online and couldn’t find any clear answer. I saw a solution that suggested I should put my schema on a server and access it with an URL address but I prefer not to do it on this point.

Also, at some point, I saved the scheme in a variable and then put it in the $ref and it worked fine. The only problem was that the scheme included some inner refs to an element in the same file and Swagger couldn't resolve them.

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


回答1:


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.



来源:https://stackoverflow.com/questions/53968759/how-to-use-ref-in-swagger-file-properly-while-working-with-swagger-ui-express-a

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