Configure swagger to your node express application

Chanuga Tharindu
3 min readAug 11, 2023
Photo by Arisa Chattasa on Unsplash

What is swagger ?

Swagger, now known as the OpenAPI Specification, is an open-source framework that provides a standardized way to document and define APIs. It allows developers to describe the structure of their APIs, including endpoints, request/response formats, authentication methods, and more.

This documentation can then be used to generate interactive documentation, client SDKs, and even server code stubs.

The key components of the Swagger/OpenAPI Specification.

  • API Endpoints : Describes the different endpoints (URLs) that your API exposes. Each endpoint specifies its HTTP method (GET, POST, PUT, DELETE, etc.), input parameters, and expected response.
  • Request and Response Formats: Specifies the format of data that can be sent to the API (request) and the format of data returned by the API (response). This includes data types, structures, and examples.
  • Authentication and Authorization: Defines how authentication and authorization are handled for each API endpoint. This can include information on API keys, tokens, or other authentication mechanisms.
  • Models and Schemas: Describes the data models used in the API, including the structure of different objects or entities exchanged between the client and the server.
  • Error Handling: Provides information about the possible error responses that an API might return and their meanings.
  • Metadata: Contains general information about the API, such as its title, version, description, and contact information.

The Swagger/OpenAPI Specification is typically written using JSON or YAML syntax. This specification can then be used by various tools to generate documentation and code. One of the most popular tools for generating interactive API documentation from Swagger/OpenAPI specs is Swagger UI.

By using Swagger/OpenAPI, developers can ensure that their APIs are well-documented, self-explanatory, and easy to understand for both internal teams and external developers who want to use the API. It also facilitates collaboration between frontend and backend teams, as they can have a shared understanding of the API’s structure and behavior.

To configure swagger to your node express application you should run,

npm install swagger-jsdoc swagger-ui-express

Then you should import swagger-jsdoc and swagger-ui-express packages to your starting point. (it is server.js for me).

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

Then we can configure the options for swagger.

// Swagger configuration options
const swaggerOptions = {
swaggerDefinition: {
openapi: '3.0.0',
info: {
title: 'Medi Balance',
version: '1.0.0',
description: 'API documentation for Medi Balance',
},
},
// If you define the routes in server.js you can add apis as
apis: ['server.js'],

// If not you should specify your route path correctly as below
// Use a glob pattern to include all route files in the routes directory
apis: [path.join(__dirname, 'routes', '*.js')],
};

After that you can use JSDoc comments in your route files.

// routes/userRoutes.mjs

/**
* @swagger
* tags:
* name: Users
* description: User management
*/

/**
* @swagger
* /api/users:
* get:
* summary: Get a list of users
* description: Retrieve a list of user profiles.
* tags: [Users]
* responses:
* 200:
* description: A list of users.
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: '#/components/schemas/User'
*/

/**
* @swagger
* components:
* schemas:
* User:
* type: object
* properties:
* id:
* type: string
* description: The user ID
* username:
* type: string
* description: The username
* email:
* type: string
* description: The email address
*/

import express from 'express';
const router = express.Router();

// Route logic here

export default router;

After that we can initialize swagger in server.js file and finally you can add a end-point to serve swagger UI to your application.

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

Now once visit that endpoint using a browser you will be able to see the documentation that you have created.

Thanks for reading

Cheers….

--

--