Skip to main content

simple and best way to document a rest api created in nodejs

The best and simplest way to document a Node.js REST API is to use the Swagger/OpenAPI specification with tools like swagger-jsdoc and swagger-ui-express. This approach involves writing documentation in a standard format (like a JavaScript/JSDoc comment block) that the swagger-jsdoc package parses into an OpenAPI specification. The swagger-ui-express package then serves this specification to generate an interactive and user-friendly documentation UI. 



1. Set up your project

  • Initialize your project:
    bash
  • mkdir my-api
    cd my-api
    npm init -y
    
  • Install necessary packages:
    bash
  • npm install express swagger-ui-express swagger-jsdoc
    
  • Create a basic Express server (app.js):
    javascript
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});

 


2. Define the API documentation 

  • Create a file for your documentation specification (e.g., swaggerDocs.js):
    javascript
  • const swaggerJsdoc = require('swagger-jsdoc');
    
    const options = {
      definition: {
        openapi: '3.0.0',
        info: {
          title: 'My Node.js API',
          version: '1.0.0',
          description: 'A sample REST API for testing documentation',
        },
        servers: [
          {
            url: 'http://localhost:3000',
            description: 'Development server',
          },
        ],
      },
      apis: ['./routes/*.js'], // Path to the API routes files
    };
    
    const swaggerSpec = swaggerJsdoc(options);
    
    module.exports = swaggerSpec;
    
  • Add JSDoc comments to your route files (e.g., routes/userRoutes.js) to define the endpoints:
    javascript
// routes/userRoutes.js

/**
 * @openapi
 * /users:
 *   get:
 *     summary: Get all users
 *     tags:
 *       - Users
 *     responses:
 *       '200':
 *         description: A list of users
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 $ref: '#/components/schemas/User'
 */
// ... your router code

 


3. Integrate with your Express app 

  • Require the Swagger UI Express and your Swagger specification in your app.js file:
    javascript
const express = require('express');
const app = express();
const port = 3000;
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = require('./swaggerDocs.js'); // Path to your swaggerDocs.js

// ... (your existing code)

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

// ... (rest of your app.js)

 


4. Run the server 

  • Start your server:
    bash
  • node app.js
    
  • Access the interactive documentation by navigating to http://localhost:3000/api-docs in your browser