Nodejs swagger integration - Express Router
I am aware of configuring swagger to my NodeJs project using JSON / YAML
. Is there any way to automate the documentation like swagger doing for spring webservices.
Note: I am using Express Router to create endpoints.
Yes, the package swagger-autogen performs the automatic construction of the Swagger documentation.
First, install the package with: npm i swagger-autogen
If you have a endpoint/route file like this:
routes.js
const express = require('express')
const ToolsController = require('./controllers/ToolsController')
const router = express.Router()
const apiV1 = require('./controllers/ApiRoute1')
router.use('/v1', apiV1)
module.exports = router
Just declare a file called swagger.js
, for example, with this:
swagger.js
const swaggerAutogen = require('swagger-autogen')()
swaggerAutogen('./swagger-output.json', ['./routes.js']);
In the package.json, add a script such as:
"scripts": {
"swagger-autogen": "node ./swagger.js"
}
And run: npm run swagger-autogen
The Swagger documentation will be in the swagger-output.json.
To add descriptions, tags, summary, and so on, access the https://www.npmjs.com/package/swagger-autogen#endpoints
Examples: Links to projects that cover the simplest use of this module as well as the most complete use. See the links below:
Example using Router
Example without Router