Configure Swagger For Node.js Backend API Endpoints on Heroku
As a backend developer, documentation is one of the last task to present your API after completion and Swagger has become a standard. Adding Swagger to your Node.js application is one of the simplest things you can accomplish.
There a few options of libraries that support Swagger which is based on OpenAPI Specification: “a broadly adopted industry standard for describing modern APIs.” Swagger has a set of tools that you can use to document your API. Swagger Codegen, Swagger Editor and Swagger UI, the last which is the focus of this tutorial.
When you have completed your Node.js backend using Express, install swagger-ui-express:
npm i swagger-ui-express -S
And in your server file, import or require,
import swaggerUi from ‘swagger-ui-express’;
import swaggerDocument from ‘./swagger.json’;
The swagger.json is a json file which describes your endpoints and models. Here is an example. The most important aspects are your paths which represents your endpoints and definitions which are your models.
Next:
app.use(‘/api-docs’, swaggerUi.serve, swaggerUi.setup(swaggerDocument));
Run your application and your can see it at http://localhost:port/api-docs. You have to change the host in swagger.json when deploying on Heroku.
This is the configuration for Express framework. For Koa.js see this. For Hapi.js see and finally for next.js see. They are all similar. Happy Coding.