Oct 30, 2025

How to Document Rails APIs with OpenAPI

Dariusz Michalski

CEO

Learn effective strategies for documenting Rails APIs using OpenAPI, focusing on local Swiss standards and enhancing collaboration.

Documenting Rails APIs is essential to avoid confusion, speed up onboarding, and ensure smooth integrations. OpenAPI offers a structured, machine-readable format for defining APIs, making it easier to generate interactive documentation, client SDKs, and mock servers. For Rails developers, tools like RSwag (test-driven) and OasRails (comment-driven) streamline the process of keeping documentation accurate and aligned with the code.

Key considerations for Swiss APIs include:

  • Date formats: Use DD.MM.YYYY (e.g., 30.10.2025).

  • Currency: Display CHF values as CHF 1'234.50.

  • Numbers: Format as 1'234.50 with apostrophes for thousands.

Quick Overview:

  • Code-first approach: Use RSwag to generate OpenAPI specs from tests.

  • Design-first approach: Use tools like Bump.sh for early API planning.

  • Swiss-specific standards: Reflect local formats in examples and specs.

  • Automation: CI/CD pipelines keep documentation up to date.

By combining proper tools and workflows, Rails teams can create clear, reliable API documentation that meets local needs and simplifies collaboration with developers and partners.

Rails 7 #131 API Documentation with OpenAPI, Swagger, RSWAG. Generate manifest with ChatGPT?!

OpenAPI

Code-First vs Design-First Documentation Approaches

When documenting Rails APIs with OpenAPI, you have two main approaches to consider. Each method has its own strengths, depending on your team's workflow, project needs, and overall development philosophy.

Understanding Code-First and Design-First Methods

Code-first documentation involves generating OpenAPI specifications directly from your existing Rails code and tests. In this approach, you build your API endpoints, controllers, and tests first, then use tools to automatically extract documentation from the implemented code. This ensures that the documentation reflects the actual behaviour of your API rather than initial intentions or plans.

This method works well for teams that value speed and flexibility. It allows you to create functional endpoints, test them thoroughly, and let the documentation evolve naturally alongside the code.

Design-first documentation, on the other hand, flips the process. Here, you start by creating the OpenAPI specification before writing any code. The API contract - defining endpoints, request and response schemas, and the overall structure - serves as the foundation for development. Developers then implement the Rails controllers and logic based on this predefined specification.

This approach is particularly useful for projects involving multiple teams or external stakeholders. For example, Swiss companies collaborating with international partners often appreciate the early feedback and validation that design-first workflows enable, helping avoid costly changes later in the development process.

Each approach comes with trade-offs. Code-first methods produce documentation that mirrors the implementation but may lack the cohesive design that upfront planning brings. Design-first methods ensure a structured API design but require diligence to keep the implementation aligned with the specification as the project evolves.

Next, let’s explore the Rails tools available for both approaches.

Rails Documentation Tools Overview

For code-first workflows, RSwag is a leading choice in the Rails ecosystem. This gem integrates seamlessly with RSpec, allowing you to write request specs that simultaneously test your API and generate OpenAPI documentation. As you run your test suite, RSwag extracts key details - like endpoint information, parameter definitions, and response examples - to create detailed OpenAPI specifications.

Another code-first option is OasRails, which focuses on YARD-based annotations. Developers can add structured comments directly to their controller methods, describing endpoints, parameters, and responses. OasRails then processes these annotations to generate OpenAPI documentation.

For design-first workflows, tools like Bump.sh offer robust solutions. These platforms treat the OpenAPI specification as the central source of truth. Teams can commit their specifications to Git, review changes through standard code review processes, and automatically publish updated documentation.

Companies such as MongoDB and Elastic have successfully used design-first approaches to improve documentation accuracy and enable parallel development across teams - an approach that’s particularly beneficial for large-scale or distributed projects.

Selecting the Right Method for Your Project

Your choice between code-first and design-first methods should align with your team’s experience and workflows. For teams already writing detailed request specs, code-first tools like RSwag are a natural fit. Conversely, teams working closely with external partners often prefer design-first approaches, which support parallel development and early feedback.

The complexity of your project is another key factor. Straightforward CRUD APIs are well-suited to code-first methods, while more complex APIs with intricate business rules often benefit from the structured planning of a design-first approach.

Regulatory requirements can also influence your decision. For example, Swiss financial services companies often need to demonstrate compliance with API design standards before development, making a design-first approach more practical.

Finally, consider how frequently your API is likely to change. APIs that evolve quickly are better suited to code-first workflows, while stable interfaces intended for external users benefit from the careful planning and version control of a design-first approach.

Many teams find success by combining both methods: using design-first for new APIs and switching to code-first for ongoing maintenance once the API stabilises. With your preferred approach in mind, let’s move on to the practical steps for implementing OpenAPI documentation in Rails.

Setting Up OpenAPI Documentation in Rails

Adding OpenAPI documentation to your Rails application helps keep your API well-documented and user-friendly. Whether you choose RSwag or OasRails, both tools integrate smoothly with Rails and make the setup process manageable.

Installing and Configuring RSwag

To get started with RSwag, add the required gems to your Gemfile:

group :development, :test do
  gem 'rswag'
  gem 'rspec-rails'
end

Run bundle install to install the gems, then generate the initial configuration files with:

rails generate rswag:install

This command creates files like spec/swagger_helper.rb, where you can configure global settings such as API version, base URL, and authentication. For Swiss-specific formatting, set the locale to 'en-CH' in your application.rb:

config.i18n.default_locale = :'en-CH'

RSwag uses a DSL that combines RSpec testing with OpenAPI documentation. Here’s an example of documenting an API endpoint for a Swiss e-commerce application:

# spec/requests/orders_spec.rb
require 'swagger_helper'

RSpec.describe 'Orders API', type: :request do
  path '/api/orders' do
    get 'List all orders' do
      tags 'Orders'
      produces 'application/json'
      parameter name: :limit, in: :query, type: :integer, description: 'Number of orders to return'

      response '200', 'orders found' do
        schema type: :array, items: {
          type: :object,
          properties: {
            id: { type: :integer },
            total: { type: :string, example: '125,50 CHF' },
            customer_name: { type: :string },
            order_date: { type: :string, example: '30.10.2025' },
            status: { type: :string, enum: ['pending', 'confirmed', 'shipped'] }
          }
        }
        run_test!
      end
    end
  end
end

The run_test! method ensures your API behaves as documented. If something doesn’t match, the test will fail, highlighting discrepancies.

To generate the OpenAPI specification file, run:

rake rswag:specs:swaggerize

This creates a swagger/v1/swagger.yaml file that reflects your API, including Swiss-specific formats for dates, currency, and numbers.

Organising Files and Automating Updates

For projects catering to multiple markets or languages, structure your documentation files like this:

swagger/
├── v1/
├── en-CH/
└── swagger.yaml
└── swagger.yaml
└── v2/
    └── swagger.yaml

Store RSwag specs under spec/requests/ for each resource. To keep documentation up-to-date, automate the process using CI/CD pipelines. Here’s an example workflow for GitHub Actions:

name: API Documentation
on: [push, pull_request]

jobs:
  docs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Setup Ruby
        uses: ruby/setup-ruby@v1
        with:
          bundler-cache: true
      - name: Generate OpenAPI docs
        run: |
          bundle exec rake rswag:specs:swaggerize
      - name: Commit updated docs
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
          git add swagger/
          git diff --staged --quiet || git commit -m "Update API documentation"

This workflow ensures your documentation stays current with every push or pull request. It’s especially useful for Swiss companies needing compliance-ready API documentation.

Setting Up OasRails as an Alternative

OasRails

If you prefer a comment-based approach, OasRails might be a better fit. It generates OpenAPI 3.1 documentation directly from YARD comments in your controller code.

Install the gem by adding it to your Gemfile:

gem 'oas_rails'

Run bundle install, then enable the documentation endpoint in routes.rb:

Rails.application.routes.draw do
  mount OasRails::Engine => '/docs' if Rails.env.development?
  # your other routes
end

Document your endpoints using YARD comments with OasRails-specific tags. Here’s an example:

class OrdersController < ApplicationController
  # @summary List all orders
  # @description Retrieves a paginated list of orders with Swiss formatting
  # @parameter limit [Integer] Maximum number of orders to return (query)
  # @response 200 [Array<Order>] List of orders
  # @response_example 200 application/json
  #   [
  #     {
  #       "id": 1,
  #       "total": "125,50 CHF",
  #       "customer_name": "Hans Müller",
  #       "order_date": "30.10.2025",
  #       "status": "confirmed"
  #     }
  #   ]
  def index
    # implementation
  end
end

OasRails generates documentation dynamically. You can view it at http://localhost:3000/docs during development. For production environments, export static OpenAPI files, which can integrate with automated workflows, just like RSwag.

Both RSwag and OasRails offer reliable ways to document your API. Choose the approach that aligns with your team’s workflow - whether it’s test-driven or comment-based.

Keeping OpenAPI Documentation Current

Keeping API documentation in sync with your evolving codebase is no small feat. Relying on manual updates often leads to outdated or incomplete documentation. Instead, automating the process ensures your OpenAPI specs stay accurate as your Rails application grows.

Documentation Maintenance Strategies

Test-driven documentation with RSwag offers a proactive way to catch mismatches. By using RSwag's DSL within your RSpec tests, you create a feedback loop where documentation generation fails if it doesn't align with actual API behaviour. This means developers must update both the code and documentation simultaneously, reducing the risk of outdated specs.

The run_test! method in RSwag acts as a safeguard. If your API responses differ from the documented structure, the test fails, flagging the issue before it reaches production. This approach is especially effective for Swiss financial applications, where precision is non-negotiable - discrepancies are caught immediately, ensuring accuracy.

Comment-driven documentation with OasRails takes a different route. Here, documentation is dynamically generated from comments in your controller methods. As developers modify code, they naturally update the corresponding comments, keeping the documentation current. For example:

# Updated comment reflects new parameter
# @parameter currency [String] Currency code (CHF, EUR, USD) (query)
# @parameter date_from [String] Start date in DD.MM.YYYY format (query)
# @parameter date_to [String] End date in DD.MM.YYYY format (query)
def financial_report
  # implementation
end

To ensure this process runs smoothly, integrate documentation validation into your CI/CD pipelines. Configure the pipeline to generate documentation and fail builds if inconsistencies are detected. This prevents outdated specs from reaching your API consumers.

Managing Versions and Extending Specs

As your Rails application evolves, API versioning strategies become essential. To maintain backward compatibility while introducing new features, organise your OpenAPI files by version. For example:

swagger/
├── v1/
├── swagger.yaml
└── en-CH/
└── localised_swagger.yaml
├── v2/
└── swagger.yaml
└── v3/
    └── swagger.yaml

When rolling out a new version, copy the previous version's documentation and update it incrementally. This approach ensures existing integrations remain functional, while new users can take advantage of the latest features. For Swiss businesses, maintaining historical documentation versions is often necessary to meet compliance and audit requirements.

Extending OpenAPI specs with detailed descriptions can significantly improve the quality of your documentation. For example:

parameter name: :vat_rate, in: :query, type: :number, 
          description: 'Swiss VAT rate as decimal',
          example: 0.077

response '200', 'invoice created' do
  schema type: :object, properties: {
    invoice_number: { 
      type: :string, 
      description: 'Sequential invoice number following Swiss format',
      example: 'INV-2025-001234' 
    },
    total_amount: { 
      type: :string, 
      description: 'Total including VAT in Swiss currency format',
      example: '1\'234,50 CHF' 
    }
  }
end

Customising response schemas helps API consumers better understand how to handle complex data. Features like oneOf for polymorphic responses or allOf for inherited schemas are particularly useful when dealing with APIs that support diverse Swiss business scenarios, such as managing multiple payment methods or shipping options.

Adding Swiss Localisation to Documentation

To make your documentation more relevant to Swiss developers, adapt examples to align with local standards. For instance, ensure dates, currencies, and other formats follow Swiss conventions.

Localised error messages and validation responses should also be included in your examples. Many Swiss businesses require multilingual support, so document how your API handles language preferences. For example:

error_response:
  type: object
  properties:
    message:
      type: string
      example: "Ungültige Postleitzahl für Schweizer Adressen"
    field:
      type: string
      example: "postal_code"
    locale:
      type: string
      example: "de-CH"

This effort goes beyond formatting - it shows an understanding of local needs and makes integration smoother for Swiss development teams. By using familiar formats and conventions, developers can focus on building their applications without getting stuck on unfamiliar standards.

For Swiss companies collaborating with USEO's Ruby on Rails expertise, incorporating these localisation practices ensures your API documentation is both technically precise and locally relevant. This creates a strong foundation for digital solutions tailored to the Swiss market.

Supporting API Users with OpenAPI Documentation

Continuing from our earlier discussion on keeping OpenAPI documentation up to date, it’s clear that well-documented APIs are essential for developers to confidently explore, test, and integrate. OpenAPI documentation acts as the link between your Rails API and the developers who rely on it. Let’s dive into how interactive documentation can enhance the experience for API users.

Creating Interactive API Documentation

Interactive documentation transforms the way developers engage with your API. Instead of relying on static text, they can test API calls directly in their browser, receiving instant feedback. This not only reduces confusion but also speeds up the integration process.

If you’ve generated your OpenAPI spec using RSwag, you can use the swagger-ui_engine gem to mount Swagger UI. Add it to your Gemfile and configure a route like /api-docs to host the documentation. By pointing Swagger UI to your OpenAPI JSON file, developers can immediately begin exploring your endpoints.

For a more modern and mobile-friendly interface, consider RapiDoc. Tools like OasRails make it easy to serve RapiDoc at routes such as /docs. Once installed, simply visit localhost:8080/docs to access sleek, interactive documentation that works seamlessly across devices.

According to the Postman State of the API Report 2023, over 70% of developers view interactive documentation as a critical factor for API adoption success. Companies offering comprehensive, interactive API documentation report up to 50% faster onboarding for external developers and partners.

Interactive documentation is particularly useful for Swiss businesses catering to multilingual markets. Developers can instantly see how your API handles variations in language preferences, currency formats, and regional data requirements - without needing to write test code first.

Creating Client SDKs and Mock Servers

OpenAPI specifications offer more than just documentation - they open the door to automation, making tasks like generating client SDKs and setting up mock servers much simpler.

Tools like Speakeasy CLI and OpenAPI Generator can turn your OpenAPI spec into client SDKs for multiple programming languages. Once you’ve exported your OpenAPI spec, run the SDK generator and distribute the resulting libraries. This process ensures that your SDKs stay aligned with API updates, reducing the risk of manual coding errors. For Swiss fintech applications, these generated SDKs can even handle CHF currency formatting and Swiss banking standards right out of the box.

Mock servers are another game-changer. Tools like Prism and Stoplight use your OpenAPI spec to simulate API responses based on your defined schemas. This allows frontend teams to develop against realistic API responses even before the backend is fully implemented. It’s a great way to eliminate bottlenecks and enable parallel development workflows.

For example, running Prism on your OpenAPI YAML file lets you serve a mock API that returns Swiss-formatted data. This means frontend developers can design interfaces that correctly display CHF amounts and multilingual content while backend development continues.

Mock servers are especially valuable for Swiss companies collaborating with external partners. Instead of waiting for the complete API to be ready, partners can begin their integration work using realistic mock responses. This approach speeds up project timelines and reduces the need for constant back-and-forth coordination.

Benefits for Swiss Businesses

The advantages of these automation tools go beyond the technical realm, offering specific benefits to Swiss businesses. Regulatory compliance, multilingual support, and local formatting standards all require clear and precise API specifications.

For FINMA compliance and data protection audits, detailed OpenAPI documentation provides the transparency regulators expect. It serves as evidence of how data flows through your system, what information is collected, and how privacy controls are implemented - key elements during compliance reviews.

Managing multilingual support becomes far more straightforward with proper documentation. Swiss businesses serving German, French, and Italian-speaking customers can specify how APIs handle language preferences, return localised error messages, and format dates according to regional standards.

CHF pricing integration also benefits from this clarity. Swiss developers expect currency amounts to be formatted as "CHF 1'234.56" rather than generic decimals. Including Swiss-specific currency examples in your OpenAPI documentation ensures integration partners implement the correct formatting from the start, avoiding costly corrections later.

The benefits extend to business operations as well. Clear API documentation reduces support requests, accelerates onboarding for partners, and builds trust with external developers. For Swiss companies working internationally, offering detailed English documentation that adheres to Swiss standards showcases professionalism and attention to detail.

USEO’s expertise in Ruby on Rails development includes designing OpenAPI documentation strategies tailored to the needs of Swiss businesses. Their experience in creating scalable and compliant solutions ensures that your API documentation becomes a competitive asset, rather than just a technical requirement.

Conclusion

OpenAPI brings structure and collaboration to Rails API development, as highlighted by the strategies discussed earlier. Tools like RSwag - which focuses on test-driven documentation - and OasRails - offering dynamic generation - provide Rails developers with effective ways to create and maintain API documentation that evolves alongside their code.

The advantages of OpenAPI are evident. For instance, companies using OpenAPI for their Rails APIs report up to a 40% decrease in onboarding time for new developers and partners (Bump.sh Blog, 2023). This time-saving is especially crucial for Swiss businesses, where multilingual teams and international collaborations demand clear and precise documentation that aligns with local standards.

In Switzerland, localisation goes beyond just technical adjustments. Accurate formatting and measurements are essential to avoid misunderstandings, particularly when working with sectors like finance, healthcare, or government, where precision is critical. OpenAPI's interactive documentation also plays a key role in reducing support queries, while generated client SDKs streamline integration efforts. Mock servers allow for parallel development, and detailed specifications offer the transparency regulators require - an asset for Swiss companies navigating compliance or data protection audits.

Whether you prefer the code-first approach of RSwag or the simplicity of OasRails, keeping your documentation updated and automated can turn it into a strategic advantage rather than a maintenance challenge.

USEO, with its expertise in Ruby on Rails, specialises in creating OpenAPI documentation strategies tailored to Swiss business needs. Their experience in building scalable, compliant solutions helps drive both technical and business success in Switzerland. By adopting these approaches, businesses can see clear benefits, including a smoother developer experience, quicker onboarding for partners, and fewer support demands.

For Rails applications serving Swiss users, OpenAPI documentation isn't just helpful - it’s a key component for long-term growth and success.

FAQs

What is the difference between code-first and design-first approaches for documenting Rails APIs with OpenAPI?

The code-first approach involves writing the API code first and then generating the OpenAPI documentation directly from it. This method works well for teams already developing an existing Rails application, as it ensures the documentation stays in sync with the actual implementation. On the downside, it might not offer much room for planning or designing the API structure in advance.

In contrast, the design-first approach focuses on creating the OpenAPI specification before any code is written. This method is perfect for teams aiming to carefully map out their API structure from the beginning. It promotes early collaboration and allows for feedback during the planning stage, though it does require more effort upfront.

Each approach has its strengths, and the decision ultimately depends on your project’s objectives, deadlines, and how your team operates.

How can I adapt OpenAPI documentation for Rails APIs to meet Swiss-specific standards?

To tailor OpenAPI documentation for Rails APIs to Swiss standards, ensure that your API outputs and documentation align with local conventions. For instance, display currency in the Swiss format (e.g., CHF 1'234.56), apply the metric system for measurements, and use the dd.mm.yyyy format for dates. Numbers should follow Swiss formatting, with a single quote as the thousand separator and a period for decimals (e.g., 1'000.50). Additionally, adjust spelling and phrasing to match Swiss preferences and linguistic nuances, ensuring the content resonates with local users.

By incorporating these Swiss-specific elements, your API documentation will feel more natural and accessible to users in Switzerland, enhancing both usability and professionalism.

What are the advantages of using interactive API documentation for developers working with Rails APIs?

Interactive API documentation brings several advantages for developers working with Rails APIs:

  • Clear and Easy to Use: Well-structured documentation, complete with endpoints, parameters, and response details, makes it straightforward for developers to understand how the API works.

  • Time-Saving Tools: Features like live testing directly within the documentation let developers check API functionality on the spot, eliminating the need to jump between different tools.

  • Better Teamwork: A centralised, reliable source of information reduces confusion and errors, helping development teams stay aligned throughout the process.

With interactive documentation, Rails developers can simplify their workflow, ensure accuracy, and make the development process smoother and more efficient.

Related Blog Posts

Have a project idea? Let's talk and bring it to life

Your highly qualified specialists are here. Get in touch to see what we can do together.

Dariusz Michalski

Dariusz Michalski, CEO

dariusz@useo.pl

Konrad Pochodaj

Konrad Pochodaj, CGO

konrad@useo.pl

Have a project idea? Let's talk and bring it to life

Your highly qualified specialists are here. Get in touch to see what we can do together.

Dariusz Michalski

Dariusz Michalski, CEO

dariusz@useo.pl

Konrad Pochodaj

Konrad Pochodaj, CGO

konrad@useo.pl

Have a project idea? Let's talk and bring it to life

Your highly qualified specialists are here. Get in touch to see what we can do together.

Start a Project
our Office

ul. Ofiar Oświęcimskich 17

50-069 Wrocław, Poland

©2009 - 2025 Useo sp. z o.o.

Start a Project
our Office

ul. Ofiar Oświęcimskich 17

50-069 Wrocław, Poland

©2009 - 2025 Useo sp. z o.o.