Easy Documentation with OpenAPI for Express
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.
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 existing application and want to add documentation later. For both cases, the Swagger Editor and the OpenAPI specification are great tools.
References and Further Reading
Swagger Editor: https://github.com/swagger-api/swagger-editor
NPM package swagger-ui-express: https://github.com/scottie1984/swagger-ui-express
What is the Difference Between Swagger and OpenAPI? https://swagger.io/blog/api-strategy/difference-between-swagger-and-openapi/
This work is licensed under a Creative Commons Attribution 4.0 International License.