Skip to content

Add Swagger documentation to your Express APIs

If you are an API developer there’s no need to introduce Swagger. It’s one of the beautiful and simple ways to document your APIs. Swagger has some fantastic DIY documentation but sometimes it isn’t too straightforward when setting up with express. This tutorial focuses on documenting your express APIs with Swagger.

Install dependencies

We need two npm dependencies to make this work, swagger-ui-express and swagger-jsdoc.

Let’s install them.

npm install swagger-ui-express --save
npm install swagger-jsdoc --save

Create Swagger Specs

In your application startup file, app.js, create a spec for the Swagger docs.

const express = require("express");
const app = express();
//Other code
const swaggerJsdoc = require("swagger-jsdoc");
const swaggerUi = require("swagger-ui-express");

const swaggerSpec = swaggerJsdoc({
  swaggerDefinition: {
    openapi: "3.0.0",
    info: {
      title: "Swagger API Tutorial - Poopcode.com",
      version: "1.0.0",
      description:
        "A sample project to understand how easy it is to document and Express API",
    }
  },
  swagger: "2.0",
});

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

Now Swagger UI will be served in the path /docs.

Document your APIs using Swagger

Inside your route, you can document your APIs using Swagger Specifications which is in YAML format.

/**
 * @swagger
 * tags:
 *   name: User APIs
 *   description: APIs to handle user resources.
 */


/**
 * @swagger
 *  /api/user/{userId}:
 *    get:
 *      summary: Retrieves a user
 *      tags: [User APIs]
 *      parameters:
 *      - in: path
 *        name: userId
 *        schema:
 *          type: string
 *        required: true
 *        description: User ID
 *      responses:
 *        "200":
 *          description: Corporate org structure for a client
 */
routes.get("/:userId", userService.getUser);

Add your routes to Swagger specs

After this step, add your routes to the API array in the Swagger Specs.

apis: ["./src/routes/user.route.js"]

Now you can see your User APIs getting added to your Swagger page.

Your full Swagger spec would like this.

const express = require("express");
const app = express();
//Other code
const swaggerJsdoc = require("swagger-jsdoc");
const swaggerUi = require("swagger-ui-express");

const swaggerSpec = swaggerJsdoc({
  swaggerDefinition: {
    openapi: "3.0.0",
    info: {
      title: "Swagger API Tutorial - Poopcode.com",
      version: "1.0.0",
      description:
        "A sample project to understand how easy it is to document and Express API",
    }
  },
  swagger: "2.0",
  apis: ["./src/routes/user.route.js"]
});


app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
See also  Pass arguments to your node.js app from pm2

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.