Swagger and Rails


Swagger - a great tool for documentation your API’s - you can read more at official Github account.

I decided to implement it into my Evendy project - it’s a web application for events organizing for me and my friends.

First of all let’s add submodule with swagger-ui tool into project’s ‘public’ directory.

cd public
git submodule add git@github.com:wordnik/swagger-ui.git swagger

Great, then add new route into our routes.rb file:

get '/docs' => redirect('/swagger/dist/index.html?url=/apidocs/api-docs.json')

Excellent, now we need to describe our API, and add some configuration parameters. Let’s create initializer swagger.rb:

class Swagger::Docs::Config
  def self.base_api_controller
    BaseController
  end

  def self.transform_path(path, api_version)
    "apidocs/#{path}"
  end
end

Swagger::Docs::Config.register_apis({
  "1.0": {
    api_extension_type: :json,
    controller_base_path: '',
    base_api_controller: 'BaseController',
    api_file_path: 'public/apidocs',
    base_path: "http://api.evendy.ru",
    clean_directory: true,
    attributes: {
      info: {
        "title": "Evendy.ru API docs",
        "description": "Evendy - web service to orginize your events.",
        "contact": "kazanlug@gmail.com",
        "license": "MIT"
      }
    }
  }
})

Then into our BaseController, to use DRY declaration:

include Swagger::Docs::ImpotentMethods
class << self
  Swagger::Docs::Generator::set_real_methods

  def inherited(subclass)
    super
    subclass.class_eval do
      setup_basic_api_documentation
    end
  end

  private
  def setup_basic_api_documentation
    [:index, :show, :create, :update, :delete].each do |api_action|
      swagger_api api_action do
        param :header, 'Authorization', :string, :required, 'Authentication token'
      end
    end
  end
end

And final step - our API definition in CategoriesController:

  swagger_controller :categories, 'Categories'

  swagger_api :index do
    summary 'Get all the categories'
    notes 'Should be used for fetching all categories'
    response :unauthorized
    response :ok, "Success"
  end
  swagger_api :create do
    summary 'Creating category'
    notes 'Should be used for creating categories'
    param :form, 'category[title]', :string, :required, 'title'
    param :form, 'category[description]', :text, :required, 'description'
  end
  swagger_api :show do
    summary 'Get category'
    notes 'Should be used for fetching a category'
    param :path, :id, :string, :id
    response :unauthorized
    response :ok, "Success"
  end
  swagger_api :destroy do
    summary 'Destroy category'
    notes 'Should be used for destroying a category'
    param :path, :id, :string, :id
    response :unauthorized
    response :ok, "Success"
  end

Then just go to the your url and /docs.

SWAGGER