How to create an API using Ruby on Rails

By lmartinez, 2 February, 2022
ruby
Unsplash

 

In this blog, we will teach you to step by step how to create an API using Ruby on Rails, even without having a greater knowledge of this framework that works with the Ruby language.

 

ruby on rails

 

What is Ruby on Rails?

 

Ruby on Rails is an open-source software that users can use to develop applications and collaborate to change their code.

 

They focus on optimizing their system for the programmers, choosing convention over configuration, which has been risky but certainly works. This framework works excellent with many other technologies and allows HTML, CSS and Java to help display user interfacing. As we said, it’s a simple to use open-source framework that integrates well with other technologies and has a growing community that’s always willing to help.

 

Step by Step: Create an API Using Ruby on Rails

 

Step 1: Create a Rails API

 

To do this, in the directory of your choice you must write the following code in your terminal. This will allow you to create a new API that will be named secret_menu_api

 

#in your terminal
rails new secret_menu_api --api

 

Next, switch to the API menu by opening it by typing this in your terminal:

 

# in your terminal
cd secret_menu_api

code .

 

Step 2: Enable CORS (Cross Origin Resource Sharing)

 

CORS allows others to access your API. To prevent unwanted access to your API, Rails automatically disables CORS. In the file explorer of your newly created Rails API, expand the following directories to open the cors.rb file.

 

config>initializers>cors.rb

 

So, Uncomment lines 8-16. 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 '*'

    resources '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

 

In the 'explorer' file, scroll down and open Gemfile. Uncomment line 26, gem 'rack-cors':

 

# in Gemfile
gem 'rack-cors'

 

Do you need an API expert for your project?

Hire the best dedicated software developers here!

 

Then in the terminal run:

 

#in terminal
bundle install

 

Step 3: Create the model, controller, database migration table, and route via the Rails g resource command

 

Command syntax:

 

# in terminal
rails g resource Secret_menu_item

 

After doing this, you will notice that this command created the following files (we include the file directory on the second line):

 

A model named secret_menu_item
app>models>secret_menu_item.rb

A controller named secret_menu_items_controller.rb app>controllers>secret_menu_items_controller.rb

A route named routes.rb
config>routes.rb

A database migration table named 202042720449_create_secret_menu_items.rb
db>migrate>202042720449_create_secret_menu_items.rb

NOTE: 202042720449 is just a timestamp, your file could have a different timestamp.

 

Step 4: In this step, you have to specify the attributes and data types of a secret menu item

 

The API was designed to display useful information about items in the secret menu, so we can display such information by setting the following as attributes:

 

  • secret menu item name
  • name of the restaurant offering the secret menu item
  • menu description

 

Specify attributes

 

In your 02042720449_create_secret_menu_items.rb, you are going to copy and paste:

 

# in db>migrate>202042720449_create_secret_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

 

You should see the following in the terminal if the migration was successful:

 

# Message in your terminal

== 20200427020449 CreateSecretMenuItems: migrating =============================
-- create_table(:secret_menu_items)
   -> 0.0022s
== 20200427020449 CreateSecretMenuItems: migrated (0.0023s) ====================

 

In your db directory, you need to open schema.rb. You will notice that this file now shows its 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: Time to define index, display, create, update, and destroy actions

 

All this will allow our API to:

 

  • Index: display instances of menu items in the database
  • Show: reflect instance of a menu item
  • Create: make an instance of the menu
  • Update: update an instance of an existing menu item
  • Delete: get rid of a secret menu item

 

Copy and paste in secret_menu_intems_controller.rb.

 

#in app>controllers>secret_menu_items_controller.rb

class SecretMenuItemsController < ApplicationController
    def index
        @secretMenuItems = SecretMenuItem.all
        render json: @secretMenuItems
    end

    def show
        @secretMenuItem = SecretMenuItem.find(params[:id])
        render json: @secretMenuItem
    end

    def create
        @secretMenuItem = SecretMenuItem.create(
            menu_name:params[:menu_name],
            restaurant_name:params[:restaurant_name],
            menu_description: params[:menu_description]
        )
        render json: @secretMenuItem
    end

    def update
        @secretMenuItem = SecretMenuItem.find(params[:id])
        @secretMenuItem.update(
            menu_name:params[:menu_name],
            restaurant_name:params[:restaurant_name],
            menu_description: params[:menu_description]
        )
        render json: @secretMenuItem
    end

    def destroy
        @secretMenuItems = SecretMenuItem.all
        @secretMenuItem = SecretMenuItem.find(params[:id])
        @secretMenuItem.destroy
        render json: @secretMenuItems
    end

end

 

Step 6 - Create routes to index, show, create, update and destroy actions

 

When talking about routes, we refer to those that receive HTTP requests on the client-side, forwarding these requests to the appropriate actions. To configure them, copy and paste into your route.rb:

 

# in config>routes.rb

Rails.application.routes.draw do
  resources :secret_menu_items, only: [:index, :show, :create, :update, :destroy]
end


Step 7: Seed the data

 

Create instances of the secret menu items in the database:

 

# in db>seed.rb

menu1 = SecretMenuItem.create(menu_name: "Chipotle Nachos", restaurant_name: "Chipotle", menu_description:"Build a plate of nachos with all of your favorite fixings")
menu2 = SecretMenuItem.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 = SecretMenuItem.create(menu_name: "Skittles", restaurant_name: "Jamba Juice", menu_description:"A mixture of lemonade, lime sherbet, frozen yogurt, and strawberries")

 

Seed the date

 

# in your terminal
rails db:seed

 

Check if it was done correctly:

 

# in your terminal
rails c

# It will pull up a console
2.6.1 :002 >

 

Type SecretMenuItem.all to extract all instances of the secret menu items that were seeded:

 

# in your terminal

2.6.1 :002 > SecretMenuItem.all
   (0.5ms) SELECT sqlite_version(*)
  SecretMenuItem Load (0.2ms) SELECT "secret_menu_items".* FROM "secret_menu_items" LIMIT ? [["LIMIT", 11]]
 => #<ActiveRecord::Relation [#<SecretMenuItem id: 1, menu_name: "Chipotle Nachos", restaurant_name: "Chipotle", menu_description: "Build a plate of nachos with all of your favorite ...">, #< SecretMenuItem id: 2, menu_name: "Starbucks butterbeer Frappuccino", restaurant_name: "Starbucks", menu_description: "Combine three pumps of toffee nut syrup and three ...">, #<SecretMenuItem id: 3, menu_name: "Skittles", restaurant_name: "Jamba Juice", menu_description: "A mixture of lemonade, lime sherbet, frozen yogurt...">]>

 

If you can see all instances, then all data was successfully seeded.

 

At Rootstack, our expert developers have created APIs to solve the technological problems that our clients present. You can be part of a multicultural team of developers, just apply here and discover the benefits of one of the fastest-growing technology companies in Latin America.

 

We recommend you on video


 

Thumbnail
Image
angular
Weight
6
Hero
Title
How to create an API using Ruby on Rails
Image
Image
Text Color
White
Text Alignment
Left
Size
Medium
Overlay effect
Hide overlay effect
Date
Premium
No