How To Generate a Swagger Docs For Rails API

Making API for a Rails application is simple for a Ruby on Rails developer. In any case, how different clients/customers will know whether the API is working fine or not without a customer side application. Is there any answer for this which I can report for API inside the Rails application, The answer is yes we have numerous instruments and methodologies however I would favor swagger UI.

In this article I am going to disclose how to make Rails API documentation using swagger UI.

Prerequisites:-
I am going to use one sample posts application which serves API calls.

Gem:-
To Integrate swagger UI for Rails API I am using a gem called swagger-docs. Add this gem to your Gemfile in your application and do bundle install.

Swagger initializer file:-
After bundling the gem create an initializer in config/initializers(e.g. swagger.rb) and specify the following options:

#File config/initializers/swagger.rb
  Swagger::Docs::Config.register_apis({
  "1.0" => {
    # the extension used for the API
    :api_extension_type => :json,
    # the output location where your .json files are written to
    :api_file_path => "public/apidocs",
    # the URL base path to your API
    :base_path => "http://localhost:3000",
    # if you want to delete all .json files at each generation
    :clean_directory => true,
    # add custom attributes to api-docs
    :attributes => {
      :info => {
        "title" =>; "Your application title",
        "description" =>; "Rails API documention with Swagger UI.",
        "termsOfServiceUrl" => "",
        "contact" => ""
       }
     }
  }
})

Refer below url for the list of configarations
https://github.com/richhollis/swagger-docs#configuration-options

swagger_controller and swagger_API are helpers to provide swagger UI documentation.


module Api

module V1

  class PostsController < ApplicationController

         respond_to :json
         swagger_controller :posts, 'Post Controller'
         swagger_api :create do
               summary 'Creating posts'
               notes 'Should be used for creating posts'
               param :form, 'post[name]', :string, :required, 'name'
               param :form, 'post[publish]', :boolean, :required, 'publish'
          end
          swagger_api :index do
                summary 'Get all the posts'
                notes 'Should be used for fetching all posts'
                param :header, :Authoraization, :string, :required, 'Authoraization'
                response :unauthorized
                response :ok, "Success"
          end
          swagger_api :show do
                summary 'Get all the posts'
                notes 'Should be used for fetching a post'
                param :path, :id, :string, :id
                response :unauthorized
                response :ok, "Success"
           end
           swagger_api :destroy do
                 summary 'Destroy the post'
                 notes 'Should be used for destroying a post'
                 param :path, :id, :string, :id
                 response :unauthorized
                 response :ok, "Success"
            end
       end
   end
end

Ex:-

param :header, :Authoraization, :string, :required, 'To authorize the requests.'
param :path, :id, :integer, :required, 'post id that supposed to fetch the record'
param :form, :name, :string, :optional, 'name of the post'
param :query, :query_name, :string, :optional, 'query name'

param – Standard API parameter

 first value: parameter_type(types: form, path, header, query)
second value: name of the parameter
 third value: datatype of the parameter
 fouth value: required/optional
 fifth value: Small description about the parameter
 sixth value: list of values in sqaure brackets to hanle enums(optional)

To handle enums:-
Pass list of enum values.
Ex:-

param_list :form, :payment_type, :string, :required, 'payment type', 
[:check, :cash, :wire_transfer, :demand_draft]

Generating json files:-

rake swagger:docs (Errors are not displayed by default with this command)

To see all error messages use the command below:

SD_LOG_LEVEL=1 rake swagger:docs

Swagger UI integration

Please download swagger ui.
https://github.com/richhollis/swagger-docs-sample/tree/master/public/api

Before that please add below code to swagger.rb to
make a distinction between the APIs and API documentation paths.

class Swagger::Docs::Config
  def self.transform_path(path, api_version)
    # Make a distinction between the APIs and API documentation paths.
    "apidocs/#{path}"
  end
end

Create apidocs directory under public and api directory under apidocs.

Copy downloaded swagger-ui to the public/apidocs/api and index.html to public/apidocs.

Edit index.html
Change swagger url in window.swaggerUi function to url: “/apidocs/api-docs.json”.
It should be pointed to api-docs.json file under public/apidocs.
Because, it will generate under that path as per the configation we defined in swagger.rb

Now we all are set. IF you are running the the server stop and restart the rails server. Go to browser and try to access “http://localhost:3000/apidocs/index”. You can click on available links(show/hide, List operations, Expand Operations and Raw) on each resource(posts etc):

swagger-doc-1 swagger-doc-2

Also read : Track Changes To Your Model’s Data with Paper Trail Gem

Also read  :  Multi-tenant Architecture with PostgreSQL Schemas

Want to learn more about our Rails development skills and past projects ? Get in touch with us now !  

Subscribe For Latest Updates

Related Posts

Leave a Comment

Your email address will not be published. Required fields are marked *

en_USEnglish