Ruby on Rails is a powerful web framework, yet when creating APIs, developers usually opt for light and flexible alternatives over Rails controllers. Grape comes to the rescue! It is a DSL (Domain-Specific Language) for building RESTful APIs in Ruby. In this article, we will talk about Grape, why it’s beneficial, and how you can include it in a Rails application.
What is Grape?
Grape is a Ruby framework for creating APIs that can be utilized as a standalone API layer or mounted within a Rails application. It boasts a slim, elegant DSL for declaring endpoints and also offers features like parameters validation, versioning and middleware support.
Why Use Grape?
Compared to Rails controllers, where the purpose is to suit web applications, Grape is designed to produce APIs with less overhead. The most significant advantages are:
- Lightweight and Flexible: Grape is designed specifically for APIs and therefore is more effective than standard Rails controllers.
- Built-in Parameter Handling: Grape supports strong parameter validation and coercion with minimal boilerplate code.
- Middleware and Mounting: It can be easily plugged into a Rails app or run as a standalone API.
- Versioning Support: It is simple to support multiple API versions (v1, v2, etc.).
- Customizable Response Formats: Grape supports JSON, XML and other formats of response.
- Support for Authentication: Grape can be paired with Devise, JWT or OAuth for authentication.
Setting Up Grape in a Rails Application
1. Install Grape
Add Grape to your Rails application by including it in the Gemfile:
# Grape Framework
gem 'grape'
gem 'grape-entity'
gem 'grape_on_rails_route'
gem 'grape-swagger'
gem 'grape-swagger-rails'
# Grape Swagger
gem 'grape-swagger-entity'
gem 'grape-swagger-representable'
Run the following command to install the gem:
bundle install
2. Create a Basic API
Inside your Rails project, create a new directory app/api, and define a base API class
#app/api/base_api.rb
require ‘grape-swagger’
module Api
class BaseApi < Grape::API
format :json
version ‘v1.0’
add_swagger_documentation format: :json,
hide_documentation_path: false,
array_use_braces: true,
info: {
title: ‘Book API’,
Description: ‘Book API’
}
get :status do
{status: ‘API is running’}
end
end
end
3. Mount the API in Rails
Modify routes.rb to mount the API:
# config/routes.rb
Rails.application.routes.draw do
mount BaseAPI => '/api'
end
Now, When you start your Rails server and visit http://localhost:3000/api/status, you should see the following JSON response:
{ "status": "API is running" }
Implementing CRUD Operations with Grape
Let’s create an API for managing books. First, create a new API file to define CRUD operations
# app/api/books_api.rb
module Api
class BooksAPI < Grape::API
format :json
prefix :api
resource :books do
desc 'Return all books'
get do
present Book.all, with: BookEntity
end
desc 'Return a specific book'
params do
requires :id, type: Integer
end
get ':id' do
present Book.find(params[:id]), with: BookEntity
end
desc 'Create a new book'
params do
requires :title, type: String
requires :author, type: String
end
post do
present Book.create!(declared(params)), with: BookEntity
end
end
end
end
4. Mount the Books API
Modify base_api.rb to include the BooksAPI**
#app/api/base_api.rb
require 'grape-swagger'
module Api
class BaseApi < Grape::API
format :json
version 'v1.0'
add_swagger_documentation format: :json,
hide_documentation_path: false,
array_use_braces: true,
info: {
title: 'Book API',
Description: 'Book API'
}
get :status do
{status: 'API is running'}
end
mount BooksAPI
end
end
5. Testing the API
Start your Rails server and test the endpoints using tools like Postman or curl:
- GET /api/books —> Fetch all books.
- GET /api/books/:id —> Fetch a specific book by ID
- POST /api/books (with JSON body) —> Create a new book
Structuring API Responses with Grape Entities
Grape provides Entities to define structured JSON response for API clients. Instead of exposing raw ActiveRecord models, we can define an entity to format the response:
# app/api/entities/book_entity.rb
class BookEntity < Grape::Entity
expose :id, documentation: { type: 'Integer', desc: 'Book ID' }
expose :title, documentation: { type: 'String', desc: 'Book Title' }
expose :author, documentation: { type: 'String', desc: 'Book Author' }
end
Now, when we return a book in the API, we use present to apply the entity
Access the API Documentation
Once you restart the Rails server, visit::
http://localhost:3000/api/swagger_doc
Conclusion
Grape offers a clean, effective way to build APIs for Ruby on Rails. It provides strong features like parameter validation, authentication, versioning, and response rendering that make API development more efficient and manageable. Grape Entities provide effective management of API response, while Grape-swagger allows clean and interactive documentation of APIs.
If you require a light, flexible replacement for Rails controllers for API development, Grape is the solution. Start using Grape today and simplify your API development process!. Need Ruby experts to help you out? Book a free consulting session with Gurzu Engineers. Enjoy Coding! 😀
.………….
Gurzu is a Ruby on Rails company based in Nepal. Here at Gurzu we transform ideas into world-class products. Our professional team is fluent in 3Rs (Ruby on Rails, React and React Native). We’re ready to design, build and develop something that your users will love. We love building web applications and do so with extreme passion and craftsmanship.
Ruby is a dynamic, high-level, general-purpose programming language known for its simplicity and productivity.Explore our awesome projects on Ruby .
If you have a query, drop us a message!