Creating API Documentation Using Swagger and Node.js: A Detailed Step-by-Step Tutorial

Creating API Documentation Using Swagger and Node.js: A Detailed Step-by-Step Tutorial

Introduction

Creating API documentation using Swagger is essential in enhancing the visibility and accessibility of your API, The swagger tool helps simplify the process of sharing information on the API being developed. This will help developers, and consumers easily understand and interact with your service.

In this article, we are going to create documentation of the API created in our previous project using Swagger, Build a RESTful API.

Installation of Dependencies

The first step we need is the necessary dependencies, and they are:

npm install swagger-jsdoc swagger-ui-express

It should look like this in your project:

Creating and Modifying the files

We need to create a file called swagger.js, this is the file we will set the tool, and this is the structure for the file:

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

const options = {
  swaggerDefinition: {
    openapi: '3.0.0',
    info: {
      title: 'Task Manager API',
      description: 'Swagger Tutorial for API',
      version: '1.0.0',
    },

  },
  apis: ['./routes/taskRoutes.js'], // Path to your  API routes files
};

const swaggerSpec = swaggerJSdoc(options);

module.exports = { swaggerSpec, swaggerUi };

Next, let us modify the server.js file:

Finally, we will modify our taskRoute.js file by adding a YAML structure to give a proper description to the API's:

Testing Swagger

This is the last step, and it is to test our project, by first starting the server

node server.js

then type in the web address to access the swagger documentation: http://localhost:3000/api-docs

http://localhost:3000/api-docs/

This will allow us to see the list of APIs created with their functions and documentation.

Wrapping Up

This simple guide will help you have a broader understanding of documentation and a very easy way to go about it.

You can find the project in this Github repo.