Integrating Grape API with Swagger in a Rails Application

Total Blog Views: 53

Blog Status: publish

Created By: swaz_ahmed Created at: 03-11-2025

Tags: api Ruby on Rails GrapeAPI APIDevelopment rails-api Swagger Entity

Introduction to Grape

 

Grape is a lightweight framework for building RESTful APIs in Ruby. It is designed to be simple, flexible, and easy to integrate with Rails applications. Unlike Rails controllers, Grape provides a more modular approach to API development with built-in support for parameter validation, error handling, and response formatting.

 

Why Use Grape?

 

  • Lightweight & Flexible: Grape is minimalistic, making it easy to build APIs quickly.

  • Built-in Validations: Grape provides strong parameter validation and coercion.

  • Seamless Integration: It can work alongside Rails controllers or standalone.

  • Swagger Support: With grape-swagger, we can generate interactive API documentation effortlessly.

 

Step 1: Install Required Gems

 

To use Grape with Swagger in a Rails application, add the following gems to your Gemfile:

gem 'grape'                 # Grape framework for building APIs
gem 'grape-swagger'         # Enables Swagger documentation for Grape APIs
gem 'grape-swagger-rails'  # Provides a UI for viewing API docs in a browser
gem 'grape-entity'  # Helps structure API responses

 

 

Then, run the bundle install command:bundle install bundle install 

bundle install 

 

Step 2: Create Grape API Base Class 

 

Create a new directory app/api and inside it, create a file api.rb:

# app/api/api.rb
module Api
  class Base < Grape::API
    format :json
    desc 'Returns Hello World'
    get :hello do
      { message: 'Hello World from Grape API' }
    end
    # Add Swagger documentation
    add_swagger_documentation
  end
end

 

 

Step 3: Configure Asset Pipeline for Swagger UI 

 

To enable Swagger UI in Rails, add the following lines to your app/assets/config/manifest.js:

//= link grape_swagger_rails/application.css
//= link grape_swagger_rails/application.js

 

Step 4: Mount Grape API in Routes 

 

Modify config/routes.rb to mount the Grape API and Swagger UI:

# config/routes.rb
Rails.application.routes.draw do
  # Mounting Grape API
  mount Api::Base => '/'

  # Optionally, for Swagger UI
  mount GrapeSwaggerRails::Engine => '/swagger'
end

 

Step 5: Configure Swagger for Grape

 

Create an initializer file config/initializers/grape_swagger_rails.rb and configure Swagger:

# config/initializers/grape_swagger_rails.rb
GrapeSwaggerRails.options.url      = '/swagger_doc'  # Correct Swagger JSON URL
GrapeSwaggerRails.options.app_name = 'My API'
GrapeSwaggerRails.options.app_url  = 'http://localhost:3000'  # Ensure correct base URL
GrapeSwaggerRails.options.api_auth = 'basic'  # Enable Basic Authentication

 

 

Step 6: Understanding Grape Entities

 

What is Grape Entity?

 

Grape Entity is a gem that provides a way to present API responses in a structured format. It helps avoid exposing unnecessary attributes, ensuring that only required data is sent to the client.

 

Why Use Grape Entity?

 

  • Cleaner API Responses: It prevents exposing unnecessary or sensitive attributes.

  • Reusability: Entities can be reused across multiple API endpoints.

  • Easier Maintenance: Structured responses make API updates more manageable.

 

Directory Structure for Entities

 

Create a directory inside app/api to store entity files:

app/
  api/
    entities/
      user_entity.rb

Creating a Grape Entity

Let's define an entity for a User model:

# app/api/entities/user_entity.rb
module Entities
  class UserEntity < Grape::Entity
    expose :id, :name, :email
  end
end
 

 

Using the Entity in an API Endpoint

Modify the API to return user data using UserEntity:

# app/api/api.rb
module Api
  class Base < Grape::API
  format :json

    desc 'Returns user details'
    get :user do
      user = { id: 1, name: 'John Doe', email: '[email protected]' }
      present user, with: Entities::UserEntity
    end
    add_swagger_documentation
  end
end

Now, when you visit http://localhost:3000/user, you'll get structured data with only the specified attributes.

 

 

Step 7: Start the Rails Server

 

Run the Rails server:

 rails s

Your API is now accessible at http://localhost:3000/hello, and Swagger documentation is available at http://localhost:3000/swagger.

 

Directory Structure for Grape API​

 app/
  api/
    entities/
      user_entity.rb  # Defines structured API responses
    api.rb            # Main Grape API file

config/
  initializers/
    grape_swagger_rails.rb  # Swagger configuration

config/routes.rb            # Mounting Grape API

Gemfile                     # Dependencies including Grape and Swagger gems

 

How Grape Differs from Rails Controllers

When developing APIs in Ruby on Rails, developers typically use controllers. However, the Grape gem offers a streamlined alternative designed specifically for APIs. Unlike Rails controllers, Grape follows its own DSL (Domain-Specific Language) and does not rely on standard Rails controllers.

 

 

Key Differences Between Grape and Rails Controllers

Grape simplifies API development by removing the need for ApplicationController and providing a more flexible structure. Here’s a comparison:

Feature Rails Controller Grape API Class
Base Class ApplicationController Grape::API
Request Format HTML, JSON, XML, etc. JSON (mainly)
Routing Defined in routes.rb Defined within Grape API class
Filters before_action, after_action before, after hooks
Params Handling params.require.permit declared(params)

 

 

Conclusion

By following these steps, you have successfully set up a Grape API in a Rails application and integrated Swagger for interactive API documentation. You also learned about Grape Entities, which help structure API responses effectively. Now, you can extend your API with more endpoints, authentication, and advanced features!

 


swaz_ahmed

I am swaz_ahmed blogger on shadbox. I am influencer,content writer,author and publisher. Feel free to ask me any question and suggestions.



Comments



Buy traffic for your website

About Shadbox

we have the “Get things executed” lifestyle at our place of work. There are not any excuses, no if’s or however’s in our dictionary. committed to navigating the ship of creativity to create cell answers, we resolve the real-lifestyles troubles of our clients and their clients. Our passion for work has won us many awards, year after 12 months.

Services

Downloads