Table of Contents
Introduction
Ruby on Rails framework provides a wide range of tools right out of the box, allowing you to build complete applications very quickly. There are adapters for almost all databases available, so you don’t need to worry about anything else.
Eventually, you will need to use Ruby on Rails API if you want to add more functionality to your services. Most of the services you use on a regular basis use some third-party API to enhance their functionality. On top of that, Ruby on Rails Gems enable developers to create functionality without having to write code.
Did you think that building a Ruby on Rails API is tough?
With just basic knowledge you can build a Ruby on Rails API.
In this guide, we will discuss APIs and their benefits and also discuss one Ruby on Rails API tutorial.
What is API?
APIs are mechanisms that let two software components communicate with one another using a set of definitions and protocols.
For instance, the software system of the weather bureau contains daily weather information. Your phone’s weather app “talks” to this system via APIs to provide you with daily weather updates.
Related Post: 5 Best API Integration Tools Developers Need to Know
How do APIs work?
APIs are typically defined in terms of client and server. Applications that transmit requests and responses are referred to as clients and servers, respectively.
In the weather example, the mobile app is the client and the bureau’s weather database is the server.
The Benefits of Ruby on Rails API Development for Developers
![Guide on How to Build a Ruby on Rails API | Optymize](https://optymize.io/wp-content/uploads/2022/12/Ruby-API-Benefits-for-Developers-1024x788.jpg)
Ruby on Rails API is one of the better solutions to consider when it comes to developing API.
For example, Ruby on Rails API enables businesses to deeply incorporate cutting-edge features and functionality into the websites they are building. This means that web APIs have more customization and flexibility than the typical copy-and-paste widget alternatives.
A well-built and extensively utilized API may prove to be a very effective marketing tool, given its capacity to promote customer loyalty, generate interest in the company’s goods and services, boost website traffic, give customers practical tools, and even communicate company messaging.
Related Post: Ruby vs Python: A Head-to-Head Comparison
The Benefits of Ruby on Rails API Development for Users
Implementing the Ruby on Rails API can significantly improve a website’s overall usability and make it much more engaging and interactive.
Now that we have come across what an API is and how one works, let’s move forward and try to build one Ruby on Rails API.
Related Post: 13 Essential Ruby on Rails Interview Questions
Step-By-Step Tutorial for Building Ruby on Rails API
The goal is to create an API of menu items available at a favourite fast food restaurant. We will follow the 8 Steps to create and test API functionality.
The 8 steps are described below –
- Create one new Rails API
- Enable CORS(Cross Origin Resource Sharing)
- Create model, controller, database migration table and route via rails g resource command
- Specify attributes and datatypes of menu item
- Define index, show, create, update, and destroy actions
- Create routes for index, show, create, update, and destroy actions
- Seed data
- Fire up your server & postman to test API functionality
Prerequisite download
To test our API, we will use a free tool called Postman.
Download Postman.
STEP 1: Create a new Rails API
Create a directory for your new API, go to that directory and type the following command into the terminal.
#in your terminal
rails new menu_api –api
The above command will create a new Rails API named menu_api.
Go to the menu_api directory and open the API by typing the following into your terminal.
# in your terminal
cd secret_menu_api
code.
STEP 2: Enable CORS (Cross Origin Resource Sharing)
CORS enables third parties to use your API. Rails automatically disables CORS to prevent unauthorized access to your API. Let’s enable CORS, So that others can access our data.
Expand the following directories in your newly built Rails API’s file explorer to access the cors.rb file.
Directory: config>initializers>cors.rb
Then,
Un-comment lines 8-16(NOTE: The corresponding code is pasted below for your reference, though line numbers may change.)
On line 10, change the code (origins ‘example.com’) to (origins ‘*’) as shown below.
# in config>initializers>cors.rb
# lines 8-16
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins ‘*’
resource ‘*’,
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
In the file explorer, scroll down and open Gemfile. Un-comment line 26, gem ‘rack-cors’
# in Gemfile
gem ‘rack-cors’
The next step is to install bundle in the terminal.
#in terminal
bundle install
STEP 3: Create model, controller, database migration table and route via rails g resource command.
The command syntax that you have to use in this step is –
rails g resource (singular form of your model name)
In our case, type in the following command in the terminal.
# in terminal
rails g resource menu_item
As you can see, the following files were all instantly created by this command!
The file directory is mentioned in the second line to make it easier for you to locate these files.
1. a model called menu_item
app>models>menu_item.rb
2. a controller called menu_items_controller.rb
app>controllers>menu_items_controller.rb
3. a route called routes.rb
config>routes.rb
4. a database migration table called 20221130165925_create_menu_items.rb
db>migrate>20221130165925_create_menu_items.rb
NOTE: The timestamp 20221130165925 indicates the time and date that I created the migration file. The timestamp on your file will be different.
STEP 4: Specify attributes and datatypes of a menu item
Our API is made to show specific information about menu items. Setting the following as attributes of a menu item will allow us to display this information:
– name of the menu item
– name of the restaurant that offers menu item
– menu description
Specify attributes
In your 20221130165925_create_menu_items.rb, copy and paste the following:
# in db>migrate>20221130165925_create_menu_items.rb
class CreateSecretMenuItems < ActiveRecord::Migration[6.0]
def change
create_table :secret_menu_items do |t|
t.string :menu_name
t.string :restaurant_name
t.string :menu_description
end
end
end
Migrate your table
# in your terminal
rails db:migrate
If migration was successful, the following output should appear in your terminal.
== 20221130165925 CreateMenuItems: migrating ============================
— create_table(:secret_menu_items)
-> 0.0022s
== 20221130165925 CreateMenuItems: migrated (0.0023s) ===================
In your db directory, open schema.rb.
You will see that this file now displays your data structure.
# in db>schema.rb
ActiveRecord::Schema.define(version: 2020_05_03_161829) do
create_table “secret_menu_items”, force: :cascade do |t|
t.string “menu_name”
t.string “restaurant_name”
t.string “menu_description”
end
end
STEP 5: Define index, show, create, update, and destroy actions
These actions enable our API to:
- Index: display all instances of menu items in our database
- Show: display an instance of a menu item
- Create: create an instance of a menu item
- Update: update an instance of an existing menu item
- Delete: an instance of an existing menu item
These actions are defined in our controller in the following manner.
Copy and paste the following in your menu_items_controller.rb.
#in app>controllers>menu_items_controller.rb
class MenuItemsController < ApplicationController
def index
@MenuItems = MenuItem.all
render json: @MenuItems
end
def show
@MenuItem = MenuItem.find(params[:id])
render json: @MenuItem
end
def create
@MenuItem = MenuItem.create(
menu_name: params[:menu_name],
restaurant_name: params[:restaurant_name],
menu_description: params[:menu_description]
)
render json: @MenuItem
end
def update
@MenuItem = MenuItem.find(params[:id])
@MenuItem.update(
menu_name: params[:menu_name],
restaurant_name: params[:restaurant_name],
menu_description: params[:menu_description]
)
render json: @MenuItem
end
def destroy
@MenuItems = MenuItem.all
@MenuItem = MenuItem.find(params[:id])
@MenuItem.destroy
render json: @MenuItems
end
end
STEP 6: Create routes for index, show, create, update, and destroy actions
Routes receive HTTP requests from client and forward requests to appropriate actions defined in corresponding controllers. We need the routes to be set up for all of the actions we have defined in our controller. Setting these up is quite easy!
Copy and paste the following in your routes.rb
# in config>routes.rb
Rails.application.routes.draw do
resources :menu_items, only: [:index, :show, :create, :update, :destroy]
end
STEP 7: Seed data
1. Create some instances of your menu items in our database.
# in db>seed.rb
menu1 = MenuItem.create(menu_name: “Chipotle Nachos”, restaurant_name: “Chipotle”, menu_description:”Build a plate of nachos with all of your favorite fixings”)
menu2 = MenuItem.create(menu_name: “Starbucks butterbeer Frappuccino”, restaurant_name: “Starbucks”, menu_description:”Combine three pumps of toffee nut syrup and three pumps of caramel with a Crème Frappuccino base”)
menu3 = MenuItem.create(menu_name: “Skittles”, restaurant_name: “Jamba Juice”, menu_description:”A mixture of lemonade, lime sherbet, frozen yogurt, and strawberries”)
2. Seed your data
# in your terminal
rails db:seed
3. Check if you seeded your data correctly
# in your terminal
rails c
# It will pull up a console
2.6.1 :002 >
Type in MenuItem.all to pull all of the instances of secret menu items we just seeded.
# in your terminal
2.6.1 :002 > SecretMenuItem.all
(0.5ms) SELECT sqlite_version(*)
MenuItem Load (0.2ms) SELECT “menu_items”.* FROM “menu_items” LIMIT ? [[“LIMIT”, 11]]
=> #<ActiveRecord::Relation [#<MenuItem id: 1, menu_name: “Chipotle Nachos”, restaurant_name: “Chipotle”, menu_description: “Build a plate of nachos with all of your favorite …”>, #<MenuItem id: 2, menu_name: “Starbucks butterbeer Frappuccino”, restaurant_name: “Starbucks”, menu_description: “Combine three pumps of toffee nut syrup and three …”>, #<MenuItem id: 3, menu_name: “Skittles”, restaurant_name: “Jamba Juice”, menu_description: “A mixture of lemonade, lime sherbet, frozen yogurt…”>]>
If you see all of the instances of our menu items, our data has been seeded correctly!
STEP 8: Fire up your server & postman to test API functionality
Run the following command in your terminal to run your server.
#in your terminal
rails s
Download and Open Postman
Postman is a useful tool to test our API functionality.
POSTMAN LAYOUT
When you open Postman you will see a gray bar between two buttons(GET and Send).
GET is an HTTP method button. If you click on the downward facing arrow, you will see drop down options for other HTTP methods.
We will be using different HTTP methods to test different actions of our API (more on that later!).
To the right of our HTTP method button, you will see a gray bar with a placeholder “Enter request URL”. This is where we will enter the URL of our API server.
To the right of the URL bar, you will see a blue send button.
Click on the send button after you have set up all the necessary parameters to test your API functionality.
Related Post: Ruby on Rails VS Node JS: An In-Depth Comparison
Conclusion
The application of APIs is never-ending. If you want to create dynamic and robust applications for your customers, spend some time researching how APIs are developed. Hire expert ruby on rails developer with working experience on APIs.
Ruby on Rails APIs are a great start to building an engaging application. But the use cases do not stop there.
If you are trying to build a Ruby on Rails application, then you can contact a hiring marketplace to hire top-quality developers who will use the latest technologies on Ruby on Rails and will deliver an interactive and intuitive application.