In today’s development world, one of the most important factor is to maintain proper documentation for complete life cycle of the development and it must be easy for any new developer to understand. Writing API using Grape gives you good manner of maintaining API documentation without any extra efforts and will allow you to maintain the versions also.
Why We Should Choose Grape For Building Rails API?
- It’s easy to handle API document with description without writing any separate API document.
- Easy and standard syntax of API endpoints.
- Easy way to format data for typical response.
- Adding new parameter and basic validation can be done easily.
- Definition of routes and API body is very decent and developer friendly.
- Grape API is much faster than any other API for rails application.
- Versioning support
Above are the main points that will do a great work for your API application and this are some major user centric reason that’s why we need Grape for building rails API.
What Is GRAPE?
Grape is a API framework for ruby language, it is used to write RESTful API for the existing web application that is already written in Rails or Sinatra framework. It has inbuilt option like common convention, multiple data/response format, versioning etc.
Learn To Build Rails API With Grape:
Grape Set up With Rails
Let us assume that we have two models like Book and Flow,
Let’s focus on Book Model First:
Book has_many Flow (Association)
So how you can generate it?
You can do it with below code,
rails g model Book isbn:integer title stock:integer
rails g controller Books
rails g model Flow previousStock:integer newStock:integer book:references
rails g controller Flows
add has_many :flows in book model
Now, run the migration
Let’s Add Required Gems To Use Grape
Add below code in your Gemfile.
gem 'grape', '~> 0.14.0'
gem 'grape-entity', '~> 0.7.1'
gem 'grape_on_rails_routes', '~> 0.3.2'
gem 'faker', '~> 1.9', '>= 1.9.1'
After adding gems just run bundle.
Detailed Information About Used Gems:
Grape : Grape is a API framework for ruby language, it is used to write RESTful API for the existing web application that is already written in Rails or Sinatra framework. It has inbuilt option like common convention, multiple data/response format, versioning etc..
Grape-Entity: To maintain and handle different kind of data and structure of data.
Grape On Rails Routes: To generate API routes.
Faker: Easy to populate data in database.
Populate Data In Rails DB Using Faker:
To populate the data, add below code in seeds.rb
Book.create!(isbn: Faker::Number.number(4), title: Faker::Superhero.power, stock: Faker::Number.between(2, 19))
book_ids = Book.ids
Flow.create!(book_id: book_ids.sample, newStock: Faker::Number.between(2, 15), previousStock: Faker::Number.between(2, 15))
Once it’s done you can use ‘rails console’ to check & verify the db whether the record is created or not.
All looks good now we can go for next step.
Start Building API With Grape
Step 1: Configure API
The first thing that we need to do is, we need to configure the API that is written in our application. For that we need to configure the file named application.rb
config.paths.add File.join(‘app’, ‘api’), glob: File.join(‘**’, ‘*.rb’)
config.autoload_paths += Dir[Rails.root.join(‘app’, ‘api’, ‘*’)]
this code will help application to find the API path.
Step 2: Create API Folder
We have to create API folder inside the app folder,
Inside API folder create one more folder called book_store or just run the below command
mkdir -p app/api/book_store
Next need to create a base.rb file inside book_store
mkdir -p app/api/book_store/base.rb
Add below content in base.rb
class Base < Grape::API
Step 3: Find Base Path Of API
this code will return you all the API path
Step 4: Setup Route For Grape API
Just add the below line in your routes.rb file,
mount BookStore::Base => ‘/’
This will point base.rb as base route for API application.
Step 5: Create Method With Maintaining Versioning
Run the below command to generate the api file called books.rb with maintaining V1.
mkdir -p app/api/book_store/v1
Go to books.rb and write the code below:
Step 6: Generate Routes To Access API
Use this code to generate routes to access API,
This will return you output as,
GET | /api/:version/books(.json) | v1 | Return list of books
Now you can access it from browser and can get the data from this API.
You have created a sample API using Grape….
For better understanding, i have covered basics in this blog and for more information about Grape like formatting data or entity related things, I will come with my new blog as part-2. Post me your interest in comments to come up with interesting blogs.
Latest posts by Amit Kumar (see all)
- Why Grape Is Best For Building Rails API? Learn To Build Rails API With Grape - January 29, 2019
- Everything You Must Know About Associations In Rails - December 26, 2018
- Installation And Uses Of Active Admin In Rails Application - December 3, 2018