You can add Swagger UI directly to app/views/layouts/application.html.erb using the CDN. No gem or npm package is required.
The following uses the official Swagger UI distribution from unpkg and loads your Rails application’s OpenAPI specification.
GitHub+1
1. Add to application.html.erb
Add the CSS link inside <head>:
<link
rel="stylesheet"
href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css"
/>
Add this where you want Swagger UI to appear in the page body:
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
SwaggerUIBundle({
url: "/openapi.json",
dom_id: "#swagger-ui",
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis
],
layout: "BaseLayout"
});
});
</script>
2. Configure the OpenAPI URL
Replace:
url: "/openapi.json",
with the actual URL of your OpenAPI endpoint, for example:
url: "/api-docs/openapi.json",
3. Optional: use a dedicated Rails view
I would actually recommend keeping Swagger UI out of the global application layout if you only need it on a documentation page.
For example, create:
app/views/api_docs/index.html.erb
and put the Swagger UI markup there. This avoids loading Swagger UI JavaScript on every page.
One security consideration: If your API is internal, protect the documentation route with the same authentication and authorization as the API itself. Hiding the UI does not secure the API.
How to make the route
In config/routes.rb, add:
Rails.application.routes.draw do
get "api-docs", to: "api_docs#index", as: :api_docs
end
You need a controller action for the view:
app/controllers/api_docs_controller.rb
class ApiDocsController < ApplicationController
def index
end
end
Rails will automatically render app/views/api_docs/index.html.erb.
You can then access Swagger UI at:
http://localhost:3000/api-docs
And link to it from another view:
<%= link_to "API Documentation", api_docs_path %>
Verify the route with:
bin/rails routes | grep api_docs
This follows the standard Rails routing and rendering conventions.
🤖 created with help of ai