Simplify Endpoint Documentation with Swagger-js

Introduction

When it comes to developing backend applications with Express, creating and managing endpoint documentation can be a tedious and laborious task. However, there is a solution to streamline this process: Swagger-js. In this article, we will explore how to use Swagger-js to automatically generate Swagger documentation for endpoints created in an Express project. With this powerful library, lazy backend programmers can save time and effort in creating documentation.

What is Swagger-js?

Swagger-js is a JavaScript library that allows for automatic generation of Swagger documentation for an Express project. Swagger, or the OpenAPI Specification, is a standard for documenting RESTful APIs. It provides a consistent structure for documenting APIs, including endpoints, parameters, data types, authorizations, and more. Swagger-js simplifies the creation of this documentation by automating much of the process.

Step 1: Installation and Configuration

First, ensure that you have Node.js and NPM installed on your system. Create a new Express project or use an existing one. Open a terminal window in the project folder and install Swagger-js using the following command:

npm install swagger-js

Next, create a new file named swagger.js in the project's main folder. This file will contain the Swagger-js configuration.

Step 2: Swagger-js Configuration

Open the swagger.js file and begin configuring Swagger-js. Here's an example of a basic configuration:

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

const app = express();
const port = 3000;

const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'Your Project Name',
      version: '1.0.0',
    },
  },
  apis: ['./routes/*.js'], // Path to files containing endpoint definitions
};

const specs = swaggerJsdoc(options);

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

app.listen(port, () => {
  console.log(`Greetings, Professor Falken, i'm listening on port ${port}`);
});

In this example configuration, we define the title and version of our project, as well as the path to the files containing the endpoint definitions. Make sure to adjust these values to your specific needs.

Step 3: Endpoint Definitions

Now it's time to define the endpoints in your Express project. Create a new file in the routes folder of your project, such as users.js, and define the endpoints within it. Here's an example of an endpoint definition:

/**
 * @swagger
 * /users:
 *   get:
 *     summary: Retrieve all users.
 *     responses:
 *       200:
 *         description: List of users.
 */
app.get('/users', (req, res) => {
  // Logic to retrieve all users
  res.send('List of users');
});

In this example, we define a GET endpoint that retrieves all users. Notice the use of Swagger annotations to describe the endpoint and its responses. These annotations will be used by Swagger-js to generate the documentation.

Step 4: Describing Payload and Response Codes

To describe the payload required for a call and the response codes produced by an endpoint, we add additional sections to the Swagger annotation.

Here's an example of how to describe the payload and response codes for a POST endpoint:

/**
 * @swagger
 * /users:
 *   post:
 *     summary: Create a new user.
 *     requestBody:
 *       description: Data of the user to be created.
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/User'
 *     responses:
 *       201:
 *         description: User created successfully.
 *       400:
 *         description: Invalid request.
 */
app.post('/users', (req, res) => {
  // Logic to create a new user
  res.status(201).send('User created successfully');
});

In this example, we define a POST endpoint to create a new user. We added a requestBody section to describe the request payload, which in this case is a JSON object representing a user. Additionally, we defined the 201 and 400 response codes with their respective descriptions.

Step 5: Generating the Documentation

Now that we have configured Swagger-js and defined the endpoints with payload and response code descriptions, we can generate the complete Swagger documentation. Start your Express server using the command node swagger.js and visit http://localhost:3000/api-docs in your browser. You should see the automatically generated Swagger documentation for the endpoints you have defined, including detailed payload and response code information.

Complete Project Code

Here's the complete code for the Express project, including the Swagger-js configuration and endpoint definition examples:

// Import necessary modules

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

// Initialize Express app

const app = express();
const port = 3000;

// Swagger-js Configuration

const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'Your Project Name',
      version: '1.0.0',
    },
  },
  apis: ['./routes/*.js'], // Path to files containing endpoint definitions
};

const specs = swaggerJsdoc(options);

// Endpoint for Swagger Documentation

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

// Endpoint Definitions

/**
 * @swagger
 * /users:
 *   get:
 *     summary: Retrieve all users.
 *     responses:
 *       200:
 *         description: List of users.
 */
app.get('/users', (req, res) => {
  // Logic to retrieve all users
  res.send('List of users');
});

/**
 * @swagger
 * /users:
 *   post:
 *     summary: Create a new user.
 *     requestBody:
 *       description: Data of the user to be created.
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/User'
 *     responses:
 *       201:
 *         description: User created successfully.
 *       400:
 *         description: Invalid request.
 */
app.post('/users', (req, res) => {
  // Logic to create a new user
  res.status(201).send('User created successfully');
});

// Start the Express server

app.listen(port, () => {
  console.log(`Greetings, Professor Falken, i'm listening on port ${port}`);
});

Conclusion

Thanks to Swagger-js, the process of creating endpoint documentation for an Express project becomes much simpler and more efficient. With just a few configuration steps and the use of Swagger annotations, we can automatically generate clear and consistent documentation for our APIs, including detailed descriptions of the payload and response codes. If you're a lazy backend programmer looking to save time and effort in endpoint documentation, give Swagger-js a try and streamline your workflow.

DocumentationJavaScriptProductivityServerside
Avatar for Valentino Tombesi

Written by Valentino Tombesi

Eclectic and cunning programmer, thrives on bending code to his will. Studies programming in a holistic way, finding innovative and all-encompassing solutions.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.