DEV Community

Bernhard Häussermann
Bernhard Häussermann

Posted on

Adding a Swagger UI page to your Express REST API

This article is a continuation of a series about how to build a REST API in Node.js. In the preceding article of this series we added request and response validation that is based on an OpenAPI spec of the API. We used the swagger-jsdoc package to generate this OpenAPI spec from comments in our code that annotate the REST operations.

Consumers of our API won't know how to make requests to it without some form of documentation. The /swagger.json route which we added returns the OpenAPI spec as a JSON string which serves this purpose. However, this JSON is not very easy to interpret for humans. In this article we will show how the OpenAPI spec can be used to render a Swagger UI page which serves as a more visual and interactive documentation for our API.

Add the swagger-ui-express package as a run-time dependency.

npm install --save swagger-ui-express
Enter fullscreen mode Exit fullscreen mode

Then in server.js we register Swagger UI at the route /swagger just after the statement that registers the /swagger.json route:

Loading localhost:3000/swagger in the browser will now show the Swagger UI page for our API. This will show all endpoints and operations that are available and even allow to try out the calls from the browser!

Screenshot 2021-09-08 at 11-28-29 Swagger UI

While we now have our API spec presented in a nice GUI, consumers of our API may still need access to the OpenAPI JSON definition to import into their client-side tooling. We can add a link to the already-defined /swagger.json route to the Swagger UI page by changing the previous app.use() statement to the following:

This will make Swagger UI read the API spec from the specified route and it will display a link to it on the page.

The code for the API developed in this series of articles is available on GitHub here.

Top comments (0)