Documenting your Rails API with Swagger

This blog post is about how to document a REST Api and why it is important to document an API. Also, I will present a gem, Rswag, which will ease the amount of work needed to generate Swagger documentation in a Ruby On Rails API.

We at Enova take our motto of ‘Customer First’ very seriously.  Whether it’s providing access to fast, trustworthy credit to hardworking people or providing ease of business and fast turnaround time to our ISO (Independent Sales Organization) partners, Enova is constantly innovating to deliver beyond expectations.

In this technology-driven environment, APIs are our weapon of choice. From powering our client-facing apps to providing access to aggregated data to our partners, our APIs do it all. They are scalable, secure, RESTful and provide a uniform interface to interact with. But it doesn’t matter how good an API is if it is not intuitive to use. A great API has great documentation. Great documentation makes developers happy because they make it easy to get simple answers to simple questions. They make it easy to answer the question of “What does this part of the API do?”  They make it easy to answer the question of “How do I use this API to do a common task?” And makes it easy to answer the question of “How do I get started?”

Enter Swagger.  The evolution of your API’s functionality is inevitable, but the headache of maintaining API docs doesn’t have to be. Swagger is a framework of API developer tools for the OpenAPI Specification(OAS), enabling development across the entire API lifecycle, from design and documentation, to test and deployment.

What is the OpenAPI Specification? At the heart of the Swagger tools is the OpenAPI Specification (formerly called the Swagger Specification). The specification creates the RESTful contract for your API, detailing all of its resources and operations in a human and machine readable format for easy development, discovery, and integration.

Swagger tools take the hard work out of generating and maintaining your API docs, ensuring your documentation stays up-to-date as your API evolves. Swagger Open Source Tools include:

  1. Swagger Editor – An open source editor to design, define and document RESTful APIs in the Swagger Specification
  2. Swagger Codegen – An open source code-generator to build server stubs and client SDKs directly from a Swagger defined RESTful API.
  3. Swagger UI  – An open source project to visually render documentation for an API defined with the OpenAPI (Swagger) Specification

Swagger also provides multiple community-driven tools for Ruby integration and one of the easiest to use is ‘Rswag’.  It provides Swagger tooling for Rails API’s and generates beautiful API documentation, including a UI to explore and test operations, directly from your rspec integration tests.

Rswag extends rspec-rails “request specs” with a Swagger-based DSL for describing and testing API operations. You describe your API operations with an intuitive syntax, and it automatically runs the tests. Once you have green tests, run a rake task to auto-generate corresponding Swagger files and expose them as JSON endpoints. Rswag also provides an embedded version of the Swagger UI that’s powered by the exposed JSON. This toolchain makes it seamless to go from integration specs, to living documentation for your API consumers.

Some of the benefits of using Rswag:

  1. Uses spec DSL (Domain Specific Language)
  2. Supports global API metadata
  3. Supports multiple versions of API
  4. Allows for the specification of different security schemes
  5. Allows you to describe JSON structures inline with your operation descriptions OR as referenced globals
  6. Provides several options for customizing Swagger UI
  7. Allows to serve UI Assets Directly from the Web Server

Installing Rswag is pretty straightforward. The following steps makes installing and using Rswag a cakewalk:

  1. Add the gem ‘rswag’ to your Gemfile
  2. Run the install generator
  3. Create the integration spec to describe and test your API
  4. Generate the Swagger JSON file
  5. Spin up your app and Boom!, you have Swagger documentation for your API at /api-docs

A sample integration spec that describes and tests the API:

# spec/integration/blogs_spec.rb

require 'swagger_helper'
describe 'Blogs API' do
  path '/blogs' do
    post 'Creates a blog' do
      tags 'Blogs'
      consumes 'application/json', 'application/xml'
      parameter name: :blog, in: :body, schema: {
        type: :object,
        properties: {
          title: { type: :string },
          content: { type: :string }
        },
        required: [ 'title', 'content' ]
      }

      response '201', 'blog created' do
        let(:blog) { { title: 'foo', content: 'bar' } }
        run_test!
      end

      response '422', 'invalid request' do
        let(:blog) { { title: 'foo' } }
        run_test!
      end
    end
  end

  path '/blogs/{id}' do
    get 'Retrieves a blog' do
      tags 'Blogs'
      produces 'application/json', 'application/xml'
      parameter name: :id, :in => :path, :type => :string

      response '200', 'blog found' do
        schema type: :object,
          properties: {
            id: { type: :integer },
            title: { type: :string },
            content: { type: :string }
          },
          required: [ 'id', 'title', 'content' ]
        let(:id) { Blog.create(title: 'foo', content: 'bar').id }
        run_test!
      end

      response '404', 'blog not found' do
        let(:id) { 'invalid' }
        run_test!
      end

      response '406', 'unsupported accept header' do
        let(:'Accept') { 'application/foo' }
        run_test!
      end
    end
  end
end

The overriding principle to all of this is to make life easy for developers.  Documenting an API and keeping it updated is essential. It is hard work and can be painful. Luckily there are tools to reduce the amount of work, and Rswag is a quite good solution even if it has some limitations.

We at Enova have been using Swagger Open Source tools and Rswag to build interactive documentation for a while now. It has been immensely helpful for our Partners who want to integrate with our API’s and has helped Enova deliver even more value while saving on time. Swagger has not only allowed us to seamlessly keep our API documentation updated but also provided a platform to present a viable frontend intro to our great backend capabilities — a feature that helps us become better, bigger and faster to market.

For more info on Rswag and Swagger Open Source tools, the following links would be helpful:

  1. Swagger –  https://swagger.io/
  2. Rswag –     https://github.com/domaindrivendev/rswag