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
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.
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.
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
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
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
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
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
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.
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.
Create a directory inside app/api
to store entity files:
app/ api/ entities/ user_entity.rb
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
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.
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) |
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!
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.
© Copyright Shadbox. All Rights Reserved
Rate Blog :
Share on :
Do you have any blog suggestion? please click on the link