Documenting NodeJS API using Swagger UI

Documenting NodeJS API using Swagger UI

Swagger UI is an open-source resource that allows anyone to test/run API endpoints. This is of benefit to the development team, project managers, and the end customers. There's no need for developers to share their screen and do all the demo to everyone. The implementation logic has been taken care of by the developer(s), hence Swagger helps us to visualize and interact with the API resources.

You can view this quick demo on Swagger. Our output will be the same as that of Swagger depending on the number of API endpoints.

Assuming you already have your API endpoints, we going to write the documentation that anybody can view on the browser whether on a hosted or local platform. Open your project and proceed as below.

First, install swagger-UI-express package from npmjs. This module allows you to serve auto-generated swagger-UI generated API docs from express, based on a swagger.json/swagger.yaml file. For YAML file, you will have to install yamljs package parser and encoder

NOTE: You can decide to use the .json or .yaml depending on your preference.

In your base file, the one with your endpoints, import swagger.

const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

Create a new swagger.json file inappropriate location and ensure the import is correct above. Add this contents, or close to this. This data will depend on your endpoints and model data.

I can't finish explaining the contents inside the swagger.json file, but you can go through the Swagger specification explanation.

The contents in the swagger.json are the same as those of swagger.yaml. The only difference is how you structure(syntax) of JSON and YAML files. Check on YAML syntax

Did you find this article valuable?

Support Nicanor Talks Web by becoming a sponsor. Any amount is appreciated!