简体   繁体   中英

How do I add Swagger to an existing Node app?

The documentation for Swagger ( https://github.com/swagger-api/swagger-node ) only shows how to create a new app. How do I integrate Swagger into an existing API app?

I followed this guide: https://blog.cloudboost.io/adding-swagger-to-existing-node-js-project-92a6624b855b

npm i swagger-ui-express -S

I used the Swagger editor to create a swagger.yml file. http://editor.swagger.io/

I added this to my server:

var swaggerUi = require('swagger-ui-express')
var fs = require('fs')
var jsyaml = require('js-yaml');
var spec = fs.readFileSync('swagger.yml', 'utf8');
var swaggerDocument = jsyaml.safeLoad(spec);
...
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

I was then able to access Swagger docs via http://localhost/api-docs .

It's unfortunately not the same level of integration that Swagger has with Spring Boot in Java, where you can add an annotation and Swagger will automatically generate the documentation for you. It seems Swagger for Node requires you to maintain the swagger.yml documentation manually. I have my routes defined like app.use('/users', userRouter) and inside the users.js file I have functions defined like router.post('/status', (req, res) => {... } . That doesn't seem compatible with Swagger for Node, which has a concept of operationId which somehow points to a function name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM