-1

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?

Chloe
  • 25,162
  • 40
  • 190
  • 357
  • Are you trying to integrate the swagger-api library (which is a framework built on top of express that handles routing) in your existing project, or do you just want to add swagger documentation files? – C Deuter Nov 06 '19 at 21:57
  • I want to both integrate the Swagger API library and created Swagger documentation files. – Chloe Nov 06 '19 at 22:26

1 Answers1

1

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.

Chloe
  • 25,162
  • 40
  • 190
  • 357