Using Swagger for Node.js APIs

Mukul Katal
2 min readOct 15, 2018

--

Swagger makes it very easy for a backend developer to document, test and explain API endpoints he/she’s been working on to a frontend developer or anyone looking to consume those endpoints.

This article explains how you can easily hook swagger into your Node.js project.

1. Setting up Swagger Editor

Install required packages:

npm i swagger swagger-editor --save-dev

Then in your package.json scripts, add the following script:

"swagger:edit": "swagger project edit"

Now you need to put your swagger.yaml config file into:

<project root dir>/api/swagger/swagger.yaml

Now you may ask why on the above mentioned path only. Well, swagger cli by default picks up config file from above mentioned path. You can modify this default path by setting “swagger_swagger_fileName” environment variable to the path wherever you put your YAML config file inside your project.

Now to test you can use sample YAML config file from here and run command:

npm run swagger:edit

2. Converting swagger.yaml to swagger.json

Since Swagger UI uses JSON file instead of YAML, you can easily setup a npm script to generate swagger.json file from your swagger.yaml config file.

Install following package:

npm i js-yaml --save-dev

Then in your package.json update the scripts to include the following:

"swagger": "js-yaml ./api/swagger/swagger.yaml > swagger.json",
"start": "npm run swagger && node ./bin/www"

Now whenever you start your app using npm start, your swagger.json will be created alongside your app.js file to power the Swagger UI. Next step explains how you can setup Swagger UI.

3. Setting up Swagger UI

Swagger UI can be set in both frontend as well as backend. Since this article is about Swagger with Node.js, I will be setting up Swagger UI in Node.js express app only. You can however explore other options here.

Install the following package:

npm i swagger-ui-express --save

In your app.js:

var express = require('express');
var app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDoc = require('./swagger.json');
//v1 api routes
app.use('/api/v1/', require('./routes/v1'));
app.use('/docs/v1/', swaggerUi.serve, swaggerUi.setup(swaggerDoc));

Voilà! thats all folks🎉🎉

Now you can npm start your app and go to http[s]://host:port/docs/v1 and you will see Swagger UI based on your generated swagger.json.

There are plenty of options available to customize Swagger UI. You can read about them here.

Use Swagger Docs and design your APIs using OpenAPI specification by putting them in your swagger.yaml file and let the Swagger UI speak for you 😉.

Checkout Github Repo

--

--