Include swagger-ui as Rails engine and document your API with simple YAML files. Supports API documentation versioning.
Swagger UI version | Rails version |
---|---|
2.2.10 | 5.0.2 (>= 4.2.6) |
Working on a Rails API, I've wanted to document my endpoints in the clearest and easiest way possible. My goal was to have the documentation separated from the actual code base and to have a web UI version of Swagger for testing and reading it. Using Rails 5 default API, I didn't need to include Grape, so I took a look into some other existing solutions. Most of them were no longer supported (e.g. swagger_engine and swagger-ui_rails) or required adding some extra code for the actual documentation (e.g. swagger-docs). Also, none of them supported Swagger web UI configuration, so I decided to write and maintain a gem on my own that would allow others to include Swagger web UI as Rails engine and support writing simple documentation in YAML files.
Add to Gemfile
gem 'swagger_ui_engine'
And then run:
$ bundle
Add to your config/routes.rb
mount SwaggerUiEngine::Engine, at: "/api_docs"
You can place this route under admin_constraint
or other restricted path, or configure basic HTTP authentication.
Set admin username and password in an initializer:
# config/initializers/swagger_ui_engine.rb
SwaggerUiEngine.configure do |config|
config.admin_username = ENV['ADMIN_USERNAME']
config.admin_password = ENV['ADMIN_PASSWORD']
end
Set the path of your json/yaml versioned documentations in an initializer:
# config/initializers/swagger_ui_engine.rb
SwaggerUiEngine.configure do |config|
config.swagger_url = {
v1: 'api/v1/swagger.yaml',
v2: 'api/v2/swagger.yaml',
}
end
and place your main documentation file under /public/api
path.
Config Name | Swagger parameter name | Description |
---|---|---|
config.swagger_url | url | The url pointing swagger.yaml (Swagger 2.0) as per OpenAPI Spec. This params requires hash value - pass your API doc version name as a key and it's main documentation url as a value. |
config.doc_expansion | docExpansion | Controls how the API listing is displayed. It can be set to 'none' (default), 'list' (shows operations for each resource), or 'full' (fully expanded: shows operations and their details). |
config.model_rendering | defaultModelRendering | Controls how models are shown when the API is first rendered. It can be set to 'model' or 'schema', and the default is 'schema'. |
config.request_headers | showRequestHeaders | Whether or not to show the headers that were sent when making a request via the 'Try it out!' option. Defaults to false . |
config.json_editor | jsonEditor | Enables a graphical view for editing complex bodies. Defaults to false . |
config.validator_enabled | validatorUrl | Enables documentation validator. Defaults to false (validatorUrl: 'null' ). |
You can use Swagger editor to write and validate your Swagger docs.
Here's an example use of SwaggerUiEngine in Rails application.
This project is available under MIT-LICENSE. ☀️