API Documentation Examples with Swagger for Node.js

Learn how to create simple API documentation with Swagger for Node.js through practical examples.
By Taylor

Introduction

Creating API documentation is crucial for developers to understand how to use your API effectively. Swagger is a powerful tool that allows you to define, document, and visualize your APIs in an easy-to-understand manner. In this article, we’ll explore three practical examples of creating simple API documentation with Swagger for Node.js. Let’s dive in!

Example 1: Basic User API Documentation

Context

Imagine you have a simple user management API that allows you to create, read, update, and delete user information. This example demonstrates how to document these endpoints using Swagger.

const express = require('express');
const swaggerJsDoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');

const app = express();
app.use(express.json());

// Swagger definition
const swaggerOptions = {
  swaggerDefinition: {
    openapi: '3.0.0',
    info: {
      title: 'User API',
      version: '1.0.0',
      description: 'A simple API to manage users',
    },
  },
  apis: ['./routes/*.js'],
};

const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));

// Sample endpoints
app.post('/users', (req, res) => {
  // Create user logic
});

app.get('/users/:id', (req, res) => {
  // Get user by ID logic
});

app.put('/users/:id', (req, res) => {
  // Update user logic
});

app.delete('/users/:id', (req, res) => {
  // Delete user logic
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Notes

  • Ensure your API endpoints are defined in separate files and referenced in the apis option of swaggerOptions.
  • You can add more detailed descriptions for each endpoint using Swagger annotations.

Example 2: Product API with Detailed Documentation

Context

Now, let’s say you have a product API that allows users to manage products in an online store. This example highlights how to document this API with more detailed descriptions and responses.

const express = require('express');
const swaggerJsDoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');

const app = express();
app.use(express.json());

const swaggerOptions = {
  swaggerDefinition: {
    openapi: '3.0.0',
    info: {
      title: 'Product API',
      version: '1.0.0',
      description: 'API for managing products',
    },
  },
  apis: ['./routes/*.js'],
};

const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));

/**

 * @swagger
 * /products:
 *   get:
 *     summary: Retrieve a list of products
 *     responses:
 *       200:
 *         description: A list of products
 */
app.get('/products', (req, res) => {
  // Logic to fetch products
});

/**

 * @swagger
 * /products:
 *   post:
 *     summary: Create a new product
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               price:
 *                 type: number
 *     responses:
 *       201:
 *         description: Product created successfully
 */
app.post('/products', (req, res) => {
  // Logic to create a product
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Notes

  • Make sure to add Swagger annotations for each endpoint to enhance the documentation.
  • You can customize response codes and descriptions based on your API’s functionality.

Example 3: Book API with Authentication

Context

In this final example, we’ll create an API for managing books in a library, incorporating authentication into our documentation. This is essential if your API requires user authentication.

const express = require('express');
const swaggerJsDoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');

const app = express();
app.use(express.json());

const swaggerOptions = {
  swaggerDefinition: {
    openapi: '3.0.0',
    info: {
      title: 'Book API',
      version: '1.0.0',
      description: 'API for managing books with authentication',
    },
  },
  apis: ['./routes/*.js'],
};

const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));

/**

 * @swagger
 * /books:
 *   get:
 *     summary: Retrieve a list of books
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: A list of books
 */
app.get('/books', (req, res) => {
  // Logic to fetch books
});

/**

 * @swagger
 * /books:
 *   post:
 *     summary: Create a new book
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               title:
 *                 type: string
 *               author:
 *                 type: string
 *     responses:
 *       201:
 *         description: Book created successfully
 */
app.post('/books', (req, res) => {
  // Logic to create a book
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Notes

  • Be sure to include security definitions for endpoints that require authentication.
  • You can expand the API documentation to include error responses and additional metadata as needed.

Conclusion

Creating API documentation with Swagger for Node.js may seem daunting at first, but by following these examples, you can effectively document your APIs. This not only helps other developers use your API but also improves your project’s overall quality. Happy coding!