Setting up OpenAPI (Swagger) in your Express app allows you to generate interactive API documentation. Follow these steps to integrate OpenAPI with your Express app.


1. Install Dependencies

You’ll need the following npm packages:

npm install swagger-ui-express swagger-jsdoc
  • swagger-ui-express: Serves the Swagger UI.
  • swagger-jsdoc: Generates the OpenAPI specification from JSDoc comments in your code.

2. Create the Swagger Configuration

Create a new file named swaggerConfig.js to define your OpenAPI specification:

import exp from 'constants';
import swaggerJsDoc from 'swagger-jsdoc';

const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'Instaverse API Documentation',
      version: '1.0.0',
      description: 'API documentation for Instaverse app',
    },
    components: {
        securitySchemes: {
          bearerAuth: {
            type: 'http',
            scheme: 'bearer',
            bearerFormat: 'JWT',
          },
        },
      },
      security: [
        {
          bearerAuth: [],
        },
      ],
      tags: [
        {
          name: 'Profile',
          description: 'Operations related to user profiles',
        },
        {
          name: 'Stories',
          description: 'Operations related to user stories',
        },
      ],
    servers: [
      {
        url: 'http://localhost:5001', // Your server URL
        description: 'Local server',
      },
    ],
  },
  apis: ['./routes/*.js'], // Path to the API docs
};

const swaggerSpec = swaggerJsDoc(options);

export default swaggerSpec;

3. Integrate Swagger UI in Your Express App

Modify your index.js or app.js file to serve the Swagger UI:

import express from 'express';
import swaggerUi from 'swagger-ui-express';
import swaggerSpec from './swaggerConfig.js';

import storyRoutes from './routes/stories.js';
import userRoutes from './routes/users.js';
import profileRoutes from './routes/profile.js';

const app = express();

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

4. Add JSDoc Annotations to Your Routes

To generate the API documentation, add JSDoc comments to your route handlers. For example:

import { Router } from "express";
import { login, signup, deleteUser, updateUserProfile } from "../controlers/users.js";
import authentication from '../midlewares/authentication.js'

const router = Router();

/**
 * @openapi
 * /user/login:
 *   post:
 *     summary: Login user and return a token.
 *     tags:
 *       - User
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               email:
 *                 type: string
 *                 example: "user@example.com"
 *               password:
 *                 type: string
 *                 example: "password123"
 *     responses:
 *       200:
 *         description: Successfully logged in, returning JWT token.
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 token:
 *                   type: string
 *                   description: JWT token for user authentication.
 *       401:
 *         description: Invalid credentials.
 */
router.post("/login", login);

export default router;

5. Test the Setup

  1. Start your Express server:
    npm start
  2. Open your browser and navigate to:
    http://localhost:5001/api-docs
  3. You should see the Swagger UI with interactive documentation for your /login endpoint.

This setup gives you a clean, organized way to document your API using OpenAPI/Swagger. Feel free checkout my personal project with this change.