Many developers know how important it's to use documentation for the API and keep it up to date. In our projects when we have a REST API we're using Swagger as it's very helpful tool for the integration process of front-end part of the system with the back-end. There is a great gem for the Ruby on Rails projects which allows to have Swagger docs with pretty standard UI - Rswag. Besides the API docs it also provides test functionality to implement some kind of integration specs for your endpoints.
But there is a problem which may occur from time to time - documentation is getting outdated. This could be related with the case when developer didn't update the source with the Swagger specs after some updates in endpoints or when person just forgot to run
rake rswag:specs:swaggerize. This command is used to re-generate the schema - JSON or YAML file, which is used to render the interface with the documentation.
There are couple of approaches to solve the latter issue. Firstly, we could just add the
swagger.yaml file to the
.gitignore and then set up our CI job to generate the schema file before the deploy. This could be useful if your project doesn't have a huge number of endpoints and there is no need to have actual Swagger UI during the local development process. Also you shouldn't re-run swaggerize command after each merge with some conflicts in Swagger schema.
But if you prefer to keep
swagger.yaml in the repository, then it should be rebuilt after each update of the corresponding swagger DSL. In such case we could use some simple shell command which will compare the old schema and a generated one from the new sources as a CI check during pull request validation.
Couple of examples for such commands:
runs: steps: ... - shell: bash run: cp <path_to_swagger.yaml_in_your_project> swagger.yaml - shell: bash run: | bundle exec rails rswag:specs:swaggerize diff <path_to_swagger.yaml_in_your_project> swagger.yaml
It uses simple
diff Linux command which displays the differences in the files by comparing the files line by line. Here we compare the old schema with newly generated file.
runs: steps: ... - shell: bash run: md5sum <path_to_swagger.yaml_in_your_project> > swagger-docs.md5 - shell: bash run: | bundle exec rails rswag:specs:swaggerize md5sum -c swagger-docs.md5
Here we use
md5sum command, which firstly generates checksum for the existing YAML schema and then compares this value with the newly generated swagger.yaml