# Swagger with Rails: Know your options

_How to document your API_

Author: Georg Ledermann  
Published: 2018-06-21  
Tags: Ruby on Rails, API  
Canonical: https://ledermann.dev/blog/2018/06/21/swagger-with-rails-know-your-options/

Hand-written API docs are already wrong by the time you merge. Three Rails gems generate them from the source instead, and they disagree about how.

---

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](https://swagger.io/resources/open-api/), 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](https://swagger.io/tools/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](https://github.com/richhollis/swagger-docs)
- [Swagger::Blocks](https://github.com/fotinakis/swagger-blocks)
- [rswag](https://github.com/domaindrivendev/rswag)

**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.
