kitaro-tn
10/30/2016 - 3:54 PM

RailsのAPIをswaggerでドキュメント化してみる ref: http://qiita.com/kitaro_tn/items/ace80a36ac3cfc060788

RailsのAPIをswaggerでドキュメント化してみる ref: http://qiita.com/kitaro_tn/items/ace80a36ac3cfc060788

# Swagger settings
# baseのcontrollerの指定、変換パスの設定
class Swagger::Docs::Config
  def self.base_api_controller; ActionController::API end
  def self.transform_path(path, api_version); "apidocs/#{path}" end
end

# 出力JSON設定
Swagger::Docs::Config.register_apis({
  "v1" => {
    :api_extension_type => nil,
    :api_file_path => "public/apidocs/", # JSONが置かれるPATH
    :base_path => "http://localhost:3000/", # 最後の`/`が置換されてしまうのでURLを記載
    :clean_directory => true,
    :formatting => :pretty,
    :camelize_model_properties => false,
    :controller_base_path => "",
    :attributes => {
      :info => {
        "title"       => "Books API",
        "description" => "Books operation API",
        "contact"     => "tora.1986.tatsu@gmail.com",
        "license"     => "Apache 2.0",
        "licenseUrl"  => "http://www.apache.org/licenses/LICENSE-2.0.html"
      }
    }
  }
})

GrapeSwaggerRails.options.app_name    = "Books API"
# 基盤となるJSON
GrapeSwaggerRails.options.url         = "/apidocs/api-docs.json"
# こっちの`/`は置換されないのでこれでOK
GrapeSwaggerRails.options.app_url     = "/"
  mount GrapeSwaggerRails::Engine => "/swagger"
  swagger_api :create do
    summary "Create a book image"
    consumes [ "application/json" ]
    param :body, :body, :object, :required, "Book image parameters", { "$ref": "BookImage" }
    response :ok, "Success", :BookImage
    response :not_found
    response :internal_server_error
  end


  swagger_model :BookImage do
    description "Book a object"
    property :id, :integer, :required, "Book image Id"
    property :book_id, :integer, :required, "Book Id"
    property :url, :string, :required, "Book image URL"
    property :alt, :string, :required, "Book image alt"
  end
  swagger_api :show do
    summary "Get a book"
    consumes [ "application/json" ]
    param :path, :id, :integer, :required, "Book Id"
    response :ok, "Success", :Book
    response :not_found
    response :internal_server_error
  end
  swagger_controller :Books, "Book"
# grapeは使用しないが、中にswagger-uiのassets一式が入っているので、viewに利用
gem 'grape-swagger-rails', '~> 0.3.0' 
gem 'swagger-docs', '~> 0.2.9'