Using Swagger for the First time

NSerus
3 min readApr 22, 2021

Hello Peppos!!!!

So you have made your first node.js application, and you need a way to document your methods, variables and paths to the world.

Worry no more cause the Swagger package is here to help you.

This little package makes a fancy and organized interface that shows all the documentation that you insert into it.

Here’s an example of the full project that we will do today:

Website for the API documentation Made With Swagger

Getting the packages

You first need to start a new project with:

npm init

And then get the needed packages to make a small app and the packages for swagger to work:

npm i -s express swagger-ui-express swagger-jsdoc

(after getting swagger-jsdoc, if there is any problem running the program because of it, try changing the version from 7.0.0 to 6.0.0)

Coding a small app

In this tutorial we are going to document a get method and a post method to show how to implement data with or without parameters.

But first things first we need to have an app to document.

The following code is the app without the swagger documentation, you first need to create an app.js file and the paste this code there:

After this is you only need to create the documentation…

Swagger documentation

First things first, we need to import the packages.

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

Then you need to create the title with the version of your app and add the api for swagger to document.

const swaggerOptions = {
swaggerDefinition: {
info:{
title: 'Calc API', //the title in the app
version: '1.0.0' //the version of the app
}
},
apis: ['app.js'], //the file that runs the API, this case app.js
};
In the interface is this what appears

You then need to parse this code to something that swagger-tools can read, this is done with the package swagger-jsdoc .

const swaggerCalc = swaggerJsDoc(swaggerOptions);

With the title parsed we can create a blank interface page like this:

app.use('/api-calc',swaggerUI.serve, swaggerUI.setup(swaggerCalc));

The first parameter is the app’s path, the second is necessary and the third setups the app using the options that you parsed.

Now you can document the paths of your API.

I use

This code is used to document the get method that we created:

Testing on the Web

And this code is for the post method:

Testing on the Web

After this, the documentation should be complete!!

--

--