Thomas Derflinger BlogFR

Easy Documentation with OpenAPI for Express

OpenAPI rendering of DanuBlue API

When you create a REST API for your Node Express backend you need to document it properly. This documentation is necessary, so that either external developers or colleagues in your team know what to expect from your REST contract.

OpenAPI is a standard for open documentation of REST endpoints. It evolved in the U.S. company SmartBear from the Swagger product suite. The Swagger specification that was developed by SmartBear was donated in 2015 to the Linux Foundation under the name of OpenAPI.

The OpenAPI specification is not only essential for other human developers but can also be read by computer programs to access the server application without needing access to the source code.

Today, SmartBear still continues to develop their Swagger product line and one product to easily edit an Open API specification is the Swagger Editor.

You can easily install the Swagger Editor with Docker:

docker pull swaggerapi/swagger-editor
docker run -d -p 8085:8080 swaggerapi/swagger-editor

The web interface of the editor is thus bound to port 8085 and when accessing in a browser displays an example specification in the YAML format on the left. On the right side there is the documentation rendered for the user. This documentation looks similar to the image on the top of this article.

The OpenAPI specification is not hard to understand for someone who has used or built REST APIs. Experiment with changing and adapting the template to your API. When there are errors, they will be displayed on the right side.

This rendering that you can see on the right side of the Swagger Editor, you can also easily include in your own Express REST application with an NPM package called swagger-ui-express. Swagger UI is a collection of HTML, JavaScript and CSS that generate a nice documentation.

The documentation produced by Swagger UI is usually accessible via an endpoint like /api-docs. Use the following lines in your Node Express application to read your specification from the YAML file and make it accessible to users:

const swaggerUi = require('swagger-ui-express')
const YAML = require('yamljs')
const swaggerDocument = YAML.load('./swagger/swagger.yaml')

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

This loads the YAML OpenAPI specification file in the directory ./swagger and renders it under /api-docs.

Some people will first develop the OpenAPI specification and only then start with the actual programming of the Express application. Others have an already exisiting application and want to add documentation later. For both cases, the Swagger Editor and the OpenAPI specification are great tools.

References and Further Reading

Published 23 Apr 2019

Thomas Derflinger

Thomas Derflinger

I am an independent entrepreneur and software developer.

Web is a topic I really enjoy. Let's get in touch!