Skip to content

Automate Swagger docs for Express Server

Posted on:July 31, 2023

Intro

Swagger docs are crucial for APIs as they provide a consistent way to document endpoints, parameters, and responses. The documentation is valuable for both API builders and users, allowing for easier interaction and fewer errors. Swagger docs can also generate client libraries and server stubs, saving time and improving consistency. Overall, using Swagger docs is a best practice for maintaining a high-quality API.

If you’re using simple plan express to build your API, you may miss out on the automatic swagger integration that is provided by some python libraries like FastAPI. While frameworks like NestJS offer their own plugins for openapi/swagger, if you prefer to keep your server applications simple and lightweight, give swagger-jsdoc a try.

Code

Assuming you already have your express server running, you will need to install these couple of libraries for getting started with swagger/openapi integration,

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

next let’s take one of our existing endpoints,

import express from "express";
import swaggerJsdoc from "swagger-jsdoc";
import swaggerUi from "swagger-ui-express";

const app = express();

/**
 * @openapi
 * /:
 *   get:
 *     description: Welcome to swagger-jsdoc!
 *     responses:
 *       200:
 *         description: Returns a mysterious string.
 */
app.get('/', (req, res) => {
  res.send('Hello World!');
});

const options:  = ;

const options: swaggerJsdoc.options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'Express API for Demo App',
      version: '1.0.0',
      description: 'Description of your application'
    },
  },
  // Paths to files containing OpenAPI definitions
  // apis: ['.src/routes/*.js'] - for regular JS projects
  apis: process.env.NODE_ENV === 'local'
    ? ['./src/routes/*.ts']
    : ['./build/routes/*.js']
};

const swaggerSpec = swaggerJsdoc(options);

app.get('/documentation.json', (req, res) => {
  res.setHeader('Content-Type', 'appplication/json');
  res.send(swaggerSpec);
});

app.use(
  '/api-documentation',
  swaggerUi.serve,
  swaggerUi.setup(swaggerSpec, { explorer: false })
);

Great job! You’re all set. You can start the express server and access /api-documentation to view your swagger docs.