Rails
Install
Add to your Gemfile:
gem 'rswag'
Then run:
bundle install
rails generate rswag:install
Write spec tests
Rswag generates the OpenAPI document from RSpec tests. Create a spec file:
# spec/requests/items_spec.rb
require 'swagger_helper'
RSpec.describe 'Items API', type: :request do
path '/items/{id}' do
get 'Get a single item' do
tags 'Items'
operationId 'getItem'
produces 'application/json'
parameter name: :id, in: :path, type: :integer, required: true
response '200', 'item found' do
schema type: :object,
properties: {
id: { type: :integer },
name: { type: :string }
}
let(:id) { Item.create(name: 'Widget').id }
run_test!
end
end
end
end
Generate the spec
rake rswag:specs:swaggerize
This produces swagger/v1/swagger.yaml.
Expose at /openapi.json
Mount rswag’s UI and add a JSON endpoint in config/routes.rb:
# config/routes.rb
mount Rswag::Ui::Engine => '/docs'
mount Rswag::Api::Engine => '/docs'
get '/openapi.json', to: proc { |env|
spec = YAML.load_file(Rails.root.join('swagger/v1/swagger.yaml'))
[200, { 'Content-Type' => 'application/json' }, [spec.to_json]]
}
The spec is now available at:
http://localhost:3000/openapi.json
Make it publicly accessible
Deploy your app or use a tunnel for local testing:
ngrok http 3000
# then use: https://<random>.ngrok.io/openapi.json
Verify
Visit /openapi.json in your browser. You should see a valid OpenAPI JSON document.
Paste this URL into Automiel’s import step.