sidgate sidgate - 14 days ago 5
Javascript Question

How to document existing nodejs APIs?

New to Node, and really frustrated with multiple libraries to do the same thing. I am going no where.

I have existing Node + express application, and need to integrate swagger docs.
Most useful thread I found was this one. But it just expects to have parallel api-docs.json file. This is not generated automatically.

I want to document each API in the controller, and want to generate the documents. Can someone point me to better resource?

Answer

Finally I was able to make it work with swagger-jsdoc

Steps

  • Add Swagger-UI package
  • Add swagger-ui dependency

    npm install -g swagger-ui

  • Configure swagger in your server.js file

    var swaggerJSDoc = require('swagger-jsdoc'); var options = { swaggerDefinition: { info: { title: 'Hello World', // Title (required) version: '1.0.0', // Version (required) }, }, apis: ['./routes.js'], // Path to the API docs }; var swaggerSpec = swaggerJSDoc(options); app.get('/api-docs.json', function(req, res) { res.setHeader('Content-Type', 'application/json'); res.send(swaggerSpec); }); app.use('/api/docs',express.static('./node_modules/swagger-ui/dist'));

  • Add swagger comments to your controller functions

/** * @swagger * resourcePath: /api * description: All about API */

/** * @swagger * /login: * post: * description: Login to the application * produces: * - application/json * parameters: * - name: username * description: Username to use for login. * in: formData * required: true * type: string * - name: password * description: User's password. * in: formData * required: true * type: string * responses: * 200: * description: login */ app.post('/login', function(req, res) { res.json(req.body); });