百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
R

rswag

> 编程语言
开源

无缝地为基于 Rails 的 API 添加 Swagger

2.2K stars0 点赞0 次浏览
访问官网GitHub

工具介绍

无缝地为基于 Rails 的 API 添加 Swagger

rswag

OpenApi 3.0 compatible!

Seeking maintainers! Got a pet-bug that needs fixing? Just let us know in your issue/pr that you'd like to step up to help.

Rswag extends rspec-rails "request specs" with a Swagger-based DSL for describing and testing API operations. You describe your API operations with a succinct, intuitive syntax, and it automatically runs the tests. Once you have green tests, run a rake task to auto-generate corresponding OpenAPI files and expose them as YAML or JSON endpoints. Rswag also provides an embedded version of the awesome swagger-ui that's powered by the exposed file. This toolchain makes it seamless to go from integration specs, which you're probably doing in some form already, to living documentation for your API consumers.

Api Rswag creates Swagger tooling for Rails API's. Generate beautiful API documentation, including a UI to explore and test operations, directly from your rspec integration tests.

And that's not all ...

Once you have an API that can describe itself in Swagger, you've opened the treasure chest of Swagger-based tools including a client generator that can be targeted to a wide range of popular platforms. See swagger-codegen for more details.

Table of Contents

  • rswag
    • Getting Started
    • The rspec DSL
      • Paths, Operations and Responses
      • Null Values
      • Support for oneOf, anyOf or AllOf schemas
      • Global Metadata
        • Supporting multiple versions of API
        • Formatting the description literals:
      • Specifying/Testing API Security
    • Configuration & Customization
      • Output Location for Generated OpenAPI Files
      • Input Location for Rspec Tests
      • Referenced Parameters and Schema Definitions
      • Request examples
      • Response headers
        • Nullable or Optional Response Headers
      • Response examples
      • Enable auto generation examples from responses
        • Dry Run Option
        • Running tests without documenting
          • rswag helper methods
      • Route Prefix for OpenAPI JSON Endpoints
      • Root Location for OpenAPI Files
      • Dynamic Values for OpenAPI JSON
      • Custom Headers for OpenAPI Files
      • Enable Swagger Endpoints for swagger-ui
      • Enable Simple Basic Auth for swagger-ui
      • Route Prefix for the swagger-ui
      • Customizing the swagger-ui
      • Serve UI Assets Directly from your Web Server

Getting Started

  1. Add this line to your applications Gemfile:

    gem 'rswag'
    

    or if you like to avoid loading rspec in other bundler groups load the rswag-specs component separately. Note: Adding it to the :development group is not strictly necessary, but without it, generators and rake tasks must be preceded by RAILS_ENV=test.

    # Gemfile
    gem 'rswag-api'
    gem 'rswag-ui'
    
    group :development, :test do
      gem 'rspec-rails'
      gem 'rswag-specs'
    end
    
  2. Run the install generator

    rails g rswag:install
    

    Or run the install generators for each package separately if you installed Rswag as separate gems, as indicated above:

    rails g rswag:api:install
    rails g rswag:ui:install
    RAILS_ENV=test rails g rswag:specs:install
    
  3. Create an integration spec to describe and test your API. There is also a generator which can help get you started rails generate rspec:swagger API::MyController

…

By default, the above command will create spec under spec/requests folder. You can pass an option to change this default path as in rails generate rspec:swagger API::BlogsController --spec_path integration. This will create the spec file spec/integration/blogs_spec.rb

  1. Generate the OpenAPI JSON file(s)

    rake rswag:specs:swaggerize
    

    This common command is also aliased as rake rswag.

    Or if you installed your gems separately:

    RAILS_ENV=test rails rswag
    
  2. Spin up your app and check out the awesome, auto-generated docs at /api-docs!

The rspec DSL

Paths, Operations and Responses

If you've used Swagger before, then the syntax should be very familiar. To describe your API operations, start by specifying a path and then list the supported operations (i.e. HTTP verbs) for that path. Path parameters must be surrounded by curly braces ({}). Within an operation block (see "post" or "get" in the example above), most of the fields supported by the Swagger "Operation" object are available as methods on the example group. To list (and test) the various responses for an operation, create one or more response blocks. Again, you can reference the Swagger "Response" object for available fields.

Take special note of the run_test! method that's called within each response block. This tells rswag to create and execute a corresponding example. It builds and submits a request based on parameter descriptions and corresponding values that have been provided using the request_params rspec variable. For example, the "post" description in the example above specifies a "body" parameter called "blog". It also lists 2 different responses. For the success case (i.e. the 201 response), notice how request_params is used to set the blog parameter to a value that matches the provided schema. For the failure case (i.e. the 422 response), notice how it's set to a value that does not match the provided schema. When the test is executed, rswag also validates the actual response code and, where applicable, the response body against the provided JSON Schema.

If you want to add metadata to the example, you can pass keyword arguments to the run_test! method:

# to run particular test case
response '201', 'blog created' do
  run_test! focus: true
end

# to write vcr cassette
response '201', 'blog created' do
  run_test! vcr: true
end

If you want to customize the description of the generated specification, a description can be passed to run_test!

response '201', 'blog created' do
  run_test! "custom spec description"
end

If you want to do additional validation on the response, pass a block to the run_test! method:

response '201', 'blog created' do
  run_test! do |response|
    data = JSON.parse(response.body)
    expect(data['title']).to eq('foo')
  end
end

If you'd like your specs to be a little more explicit about what's going on here, you can replace the call to run_test! with equivalent "before" and "it" blocks:

response '201', 'blog created' do
  let(:request_params) { { 'blog' => { title: 'foo', content: 'bar' } } }

  before do |example|
    submit_request(example.metadata)
  end

  it 'returns a valid 201 response' do |example|
    assert_response_matches_metadata(example.metadata)
  end
end

Also note that the examples generated with run_test! are tagged with the :rswag so they can easily be filtered. E.g. rspec --tag rswag

date-time in query parameters

Input sent in queries of Rspec tests is HTML safe, including date-time strings.

parameter name: 'date_time', in: :query, type: :string

response '200', 'blog found' do
  let(:date_time) { DateTime.new(2001, 2, 3, 4, 5, 6, '-7').to_s }
  let(:request_params) { { 'date_time' => date_time } }

  run_test! do
    expect(request[:path]).to eq('/blogs?date_time=2001-02-03T04%3A05%3A06-07%3A00')
  end
end

Enum description

If you want to output a description of each enum value, the description can be passed to each value:

parameter name: 'status', in: :query,
          enum: { 'draft': 'Retrieves draft blogs', 'published': 'Retrieves published blogs', 'archived': 'Retrieves archived blogs' },
          description: 'Filter by status'

response '200', 'success' do
  let(:request_params) { {'status' => 'published'} }

  run_test!
end

Schema validations

Additional properties

If you want to disallow additional properties in response body, you can set the option openapi_no_additional_properties to true:

# spec/swagger_helper.rb
RSpec.configure do |config|
  config.openapi_no_additional_properties = true # default false
end

You can set similarly the option per individual example as shown in Strict (deprecated) sections.

      response '200', 'blog found', :openapi_no_additional_properties do
      response '200', 'blog found', openapi_no_additional_properties: true do

All required properties

If you want to disallow missing required properties in response body, you can set the openapi_all_properties_required option to true: Important it will allow the additional properties

# spec/swagger_helper.rb
RSpec.configure do |config|
  config.openapi_all_properties_required = true # default false
end

You can set similarly the option per individual example as shown in Strict (deprecated) sections.

      response '200', 'blog found', :openapi_all_properties_required do
      response '200', 'blog found', openapi_all_properties_required: true do

Null Values

This library is currently using JSON::Draft4 for validation of response models. Nullable properties can be supported with the non-standard property 'x-nullable' to a definition to allow null/nil values to pass. Or you can add the new standard nullable property to a definition.

describe 'Blogs API' do
  path '/blogs' do
    post 'Creates a blog' do
      ...

      response '200', 'blog found' do
        schema type: :object,
          properties: {
            id: { type: :integer },
            title: { type: :string, nullable: true }, # preferred syntax
            content: { type: :string, 'x-nullable': true } # legacy syntax, but still works
          }
        ....
      end
    end
  end
end

Support for oneOf, anyOf or AllOf schemas

OpenAPI 3.0 supports more flexible schema validation with the oneOf, anyOf and allOf directives. rswag will handle these definitions and validate them properly.

Notice the schema inside the response section. Placing a schema method inside the response will validate (and fail the tests) if during the integration test run the endpoint response does not match the response schema. This test validation can handle anyOf and allOf as well. See below:

…

This automatic schema validation is a powerful feature of rswag.

Global Metadata

In addition to paths, operations and responses, OpenAPI also supports global API metadata. When you install rswag, a file called openapi_helper.rb is added to your spec folder. This is where you define one or more OpenAPI doc

GitHub Issues· 0 开放

在 GitHub 查看全部

暂无开放 Issues,或尚未同步最近议题。

核心特点

  • •Getting Started
  • •The rspec DSL
  • •Paths, Operations and Responses
  • •Null Values
  • •Support for oneOf, anyOf or AllOf schemas
  • •Global Metadata
  • •Supporting multiple versions of API
  • •Formatting the description literals:
  • •Specifying/Testing API Security
  • •Configuration & Customization

> 标签

Rubyopenapirswagswagger-ui

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言