Discussion

Adding Swagger To Existing Node.js Project

Today, almost every application has to be connected and to share data with other applications. The best way to do that is throughAPIs. For a long time there hasn’t been any industry standard for designing and documenting APIs. And API without a good documentation on how to use it, is useless. Because of that, developers have worked hard to create a standard way of describing APIs and documenting them. One such proposal is Swagger.

We can use https://www.npmjs.com/package/swagger-ui-expressswagger-ui-express for this purpose.

A community driven package that adds a middleware to your Express.js application that serves the Swagger UI bound to your Swagger document. The library is very easy to setup, you just need to add one route that will host Swagger UI, and guess what you don’t need to copy anything manually. This is an open source project and it is still actively maintained. Documentation is good and everything that you need should be there.
Given the functionality and simplicity of use we have decided to use this library in order to add documentation to our application.

First, we need to add a library to our project:
npm i swagger-ui-express -S

When the library is added to a project we need to add a route on which we will host Swagger UI. Also, we need to load the Swagger API definition of our application so that we can host it in Swagger UI

import swaggerUi from 'swagger-ui-express';
import YAML from 'yamljs';

const swaggerDoc = YAML.load(path.join(__dirname, './openapi.yaml'));

app.use('/api/doc', swaggerUi.serve, swaggerUi.setup(swaggerDoc));

Now, you can go to base_url/api/doc, then you can see the API documentation on the browser.

Yay, it works.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *