GrapeSwaggerRails

Gem Version Tests

Swagger UI as Rails Engine for grape-swagger gem.

Table of Contents

Installation

Add this line to your application's Gemfile:

gem 'grape-swagger-rails'

And then execute:

$ bundle

Or install it yourself as:

$ gem install grape-swagger-rails

Compatibility

This gem is continuously tested against the following stack:

Ruby Rails Grape grape-swagger Swagger UI
3.4 7.2.2.2 1.8.x 1.6.1 5.32.5
3.2+ 7.2.2.2 3.1.x 2.1.4 5.32.5
3.2+ 8.1.x 3.1.x 2.1.4 5.32.5

The dummy app and CI also exercise both supported Rails asset pipelines: Sprockets and Propshaft.

If you use a nearby version and hit an issue, please open one with your Gemfile.lock and a minimal reproduction.

Support Policy

grape-swagger-rails currently supports the Ruby / Rails / Grape / grape-swagger combinations listed in the tested compatibility matrix above.

The embedded Swagger UI is currently exercised against Swagger / OpenAPI 2.0 documents generated by grape-swagger. In the UI this appears as the OAS 2.0 badge.

This gem does not currently claim OpenAPI 3.x document support. If a dependency update changes the generated document format or the UI integration contract, support should only be documented after the corresponding CI lanes and feature specs pass.

Usage

Add this line to ./config/routes.rb:

mount GrapeSwaggerRails::Engine => '/swagger'

Create an initializer (e.g. ./config/initializers/swagger.rb) and specify the URL to your Swagger API schema and app:

GrapeSwaggerRails.options.url      = '/swagger_doc.json'
GrapeSwaggerRails.options.app_url  = 'http://swagger.wordnik.com'

To expose multiple API specifications in the UI, set urls instead of a single url:

GrapeSwaggerRails.options.urls = [
  { name: 'v1', url: '/api/v1/swagger_doc' },
  { name: 'v2', url: '/api/v2/swagger_doc', default: true }
]
GrapeSwaggerRails.options.app_url = 'http://localhost:3000'

When multiple specs are configured, a spec selector dropdown appears in the Swagger UI header. Mark one item with default: true to select it by default.

To pass native Swagger UI configuration options through to SwaggerUIBundle, use swagger_ui_config:

GrapeSwaggerRails.options.swagger_ui_config = {
  defaultModelsExpandDepth: -1,
  displayRequestDuration: true
}

These values are merged into the SwaggerUIBundle(...) call before the gem's own defaults, so they apply as base configuration. The gem's own options (such as url, requestInterceptor, presets) still take precedence.

You can dynamically set app_url for each request use a before_action:

GrapeSwaggerRails.options.before_action do
  GrapeSwaggerRails.options.app_url = request.protocol + request.host_with_port
end

Be careful with request-time mutation of GrapeSwaggerRails.options. This object is global process state, so mutating nested values such as app_url, headers, or authentication defaults inside before_action can leak across requests in threaded app servers.

Safer patterns:

  • Prefer assigning request-specific values directly in the controller/view path rather than mutating shared global options.
  • If you must derive request-specific values in before_action, overwrite the full value you need for that request and avoid incremental mutation of shared hashes.
  • Be especially careful with code like GrapeSwaggerRails.options.headers['X-Header'] = ..., which mutates a shared hash in place.

You can set the app name, default is "Swagger".

GrapeSwaggerRails.options.app_name = 'Swagger'

You can specify additional headers to add to each request:

GrapeSwaggerRails.options.headers['Special-Header'] = 'Some Secret Value'

You can set docExpansion with "none" or "list" or "full", default is "none". See the official Swagger-UI documentation about SwaggerUi Parameters.

GrapeSwaggerRails.options.doc_expansion = 'list'

You can set supportedSubmitMethods with an array of the supported HTTP methods, default is %w{ get post put delete patch }.

See the official Swagger-UI documentation about SwaggerUi Parameters.

GrapeSwaggerRails.options.supported_submit_methods = ["get"]

You can set validatorUrl to your own locally deployed Swagger validator, or disable validation by setting this option to nil. This is useful to avoid error messages when running Swagger-UI on a server which is not accessible from outside your network.

GrapeSwaggerRails.options.validator_url = nil

Using the headers option above, you could hard-code Basic Authentication credentials. Alternatively, you can configure Basic Authentication through the UI, as described below.

Overriding the Swagger UI Template

If you need to customize the page layout or script includes, prefer a local Rails view override instead of editing the gem's template directly.

Create a host-application view at:

app/views/grape_swagger_rails/application/index.html.haml

and copy the current engine template as a starting point. The engine's default template lives at:

app/views/grape_swagger_rails/application/index.html.haml

If you also need to customize the maintained browser runtime, reference your own asset from the overridden template instead of editing the gem asset in place. The engine's maintained runtime is:

app/assets/javascripts/grape_swagger_rails/index.js

This keeps application-specific branding and behavior changes local to the host app and makes gem upgrades easier to review.

Basic Authentication

If your application uses Basic Authentication, you can setup Swagger to send the username and password to the server with each request to your API:

GrapeSwaggerRails.options.api_auth     = 'basic' # Or 'bearer' for OAuth
GrapeSwaggerRails.options.api_key_name = 'Authorization'
GrapeSwaggerRails.options.api_key_type = 'header'

Now you can specify the username and password to your API in the Swagger "API key" field by concatenating the values like this:

username:password

The javascript that loads on the Swagger page automatically encodes the username and password and adds the authorization header to your API request. See the official Swagger documentation about Custom Header Parameters

Pre-fill Authentication

If you will know the Authentication key prior to page load or you wish to set it for debug purposes, you can setup so that the api_key field is pre-filled on page load:

GrapeSwaggerRails.options.api_key_default_value = 'your_default_value'

To set it based on the current_user or other request-based parameters, try using it inside of your before_action (See Swagger UI Authorization)

API Token Authentication

If your application uses token authentication passed as a query param, you can setup Swagger to send the API token along with each request to your API:

GrapeSwaggerRails.options.api_key_name = 'api_token'
GrapeSwaggerRails.options.api_key_type = 'query'

If your application used token authentication passed as a header, like Rails does (authenticate_or_request_with_http_token), you can configure Swagger to send the token in this form:

Authorization: Token token="WCZZYjnOQFUYfJIN2ShH1iD24UHo58A6TI"

by specify:

GrapeSwaggerRails.options.api_auth = 'token'
GrapeSwaggerRails.options.api_key_name = 'Authorization'
GrapeSwaggerRails.options.api_key_type = 'header'
GrapeSwaggerRails.options.api_key_placeholder = 'authorization_token'

You can use the authorization_token input box to fill in your API token.

Swagger UI Authorization

You may want to authenticate users before displaying the Swagger UI, particularly when the API is protected by Basic Authentication. Use the before option to inspect the request before Swagger UI:

GrapeSwaggerRails.options.before_action do |request|
  # 1. Inspect the `request` or access the Swagger UI controller via `self`.
  # 2. Check `current_user` or `can? :access, :api`, etc.
  # 3. Redirect or error in case of failure.
end

Integration with DoorKeeper

Add the following code to the initializer (swagger.rb):

GrapeSwaggerRails.options.before_action do |request|
  GrapeSwaggerRails.options.api_key_default_value = current_user.token.token
end

In your User model (user.rb) add:

has_one :token, -> { order 'created_at DESC' }, class_name: Doorkeeper::AccessToken, foreign_key: :resource_owner_id

Hiding the API or Authorization text boxes

If you know in advance that you would like to prevent changing the Swagger API URL, you can hide it using the following:

GrapeSwaggerRails.options.hide_url_input = true

Similarly, you can hide the Authentication input box by adding this:

GrapeSwaggerRails.options.hide_api_key_input = true

By default, these options are false.

Updating Swagger UI from Dist

To update Swagger UI from its distribution, run bundle exec rake swagger_ui:dist:update. Examine the changes carefully.

NOTE: This action should be run part of this gem (not your application). In case if you want to make it up-to-date, clone the repo, run the rake task, examine the diff, fix any bugs, make sure tests pass and then send PR here.

Contributors

AI Agents

If you're an AI agent working on this project, read the instructions file for your tool:

These files contain architecture context, commands, and coding conventions.

Contributing

See CONTRIBUTING.

License

MIT License, see LICENSE.