{EP}

David Perez

How to setup Swagger in NodeJS project

JavaScript

July 28, 2021

Swagger

Overview

We'll create a pretty simple NodeJS cars API and configure swagger with it. Here is the link to the GitHub repo.

Swagger and OpenAPI

OpenAPI was created as a way to standarize RESTful APIs. Its main focus is to create, evolve, and promote a vendor neutral description format. The OpenAPI Specification was originally based on the Swagger Specification.

Swagger simplifies the API development for teams and users. It's a set of tools to help you design, build, test, and document your API. Some of the tools that swagger provides are: Swagger Editor, Swagger UI, and Swagger Codegen.

For our purposes, we'll be using a couple libraries that helps us create swagger UI from an NodeJS express API.

Setup

Let's start by creating the NodeJS project. On your terminal, create a directory for the project and run npm init -y. This will initialize a NodeJS project and will allow us to start installing dependencies.

Next, let's install the dependencies needed for the project, run the following commnands:

npm i -S express swagger-ui-express swagger-jsdoc

Now, you should have the dependencies needed and we can start the configuration of swagger and express.

Configuration

Create a file at the root of the project named app.js, this will be the main file for the project.

const express = require('express')
const swaggerJSDoc = require('swagger-jsdoc')
const swaggerUI = require('swagger-ui-express')

const PORT = 3000
const app = express()

/**
 * Swagger Config
 */

const swaggerOpts = {
  swaggerDefinition: {
    info: {
      title: 'Cars API',
      version: '1.0.0'
    }
  },
  // Files that contain the Swagger comments but can also give
  // general file patterns such as ./api/**/*.js
  apis: ['./app.js']
}

const swaggerDocs = swaggerJSDoc(swaggerOpts)

// Endpoint in which the swagger UI will be served at.
// We are using swagger js docs to dynamically create the swagger document.
// This document is then given to swagger ui express.
app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerDocs))

/**
 * API
 */

app.get('/', (req, res) => {
  res.send('Awesome API')
})

// Below is a sample route with swagger comment.
// Swagger JSDoc will parse the comments and create the swagger document.

/**
 * @swagger
 * /cars:
 *  get:
 *    description: Get all cars
 *    responses:
 *      200:
 *        description: Success
 */
app.get('/cars', (req, res) => {
  res.send(['car 1', 'car 2'])
})

app.listen(PORT, () => {
  console.log(`App started on: http://localhost:${PORT}`)
})

Running

Once you have created the above file, you should be able to run the project with node app.js.

If you navigate to localhost:3000/api-docs, you will see the swagger documentation for your NodeJS API.NodeJS

Swagger UI

With this, you now have a fully setup project with swagger on NodeJS. 🚀.