by Georg Ledermann

Swagger with Rails: Know your options

How to document your API

Photo by Jiroe on Unsplash

Photo by Jiroe on Unsplash

Creating API documentation is an essential task that should not be done separately from implementation. The risk that implementation and documentation may diverge should not be underestimated.

One way to document a RESTful API is to use the OpenAPI specification, also known as Swagger. This way, every detail of the API is noted in a precisely defined JSON file. There are many tools available to process this kind of JSON file – e.g. with Swagger UI there is an interactive tool to read the documentation in the browser and test the API (by building and executing curl commands).

The JSON file can be created manually, but of course, an automated generation is a more elegant way. In the world of Ruby on Rails there are two popular approaches of doing this:

  • Enhance the controller via an additional DSL, so the JSON file can be generated from the controller
  • Leave the controller unchanged, but enhance the (integration) tests so that the documentation can be generated from it

I found the following gems to support this:

Swagger::Docs is the oldest tool I found, it was born in 2013 and therefore only supports the old version v1.2 of the Swagger specification. There is no effort to support v2 or newer, which is probably the biggest disadvantage of this gem. With Swagger::Docs you write your documentation directly to the API controllers via a custom DSL. The JSON file is generated via a rake task.

Swagger::Blocks was inspired by Swagger::Docs and has been developed since 2014. It supports v2 of the specification. The documentation is added to the controller. The special feature is that the JSON file is generated on-the-fly: Instead of a rake task, the JSON file is generated at runtime.

rswag is the new kid in town (started 2016), supports v2 of to the specification and is integrated with RSpec, so the documentation is added to the integration tests. I like this approach because it forces you to test the various response options (ok, not authorized, bad request, etc.) and to ensure that the response body matches the schema. The JSON file is created by a rake task. As a bonus, Swagger UI is included.

From my point of view, rswag is the tool of choice because it best ensures that documentation and implementation fit together.