Ruby VII | Rails API 💻

Milan Parmar
3 min readFeb 7, 2021

Welcome to the seventh instalment in my Ruby series…Building an API using Rails!

For my last project with Flatiron, I created an application for Samsung called Your Galaxy. The purpose of the application was to gain customer feedback on Galaxy devices, namely pros and cons and have users log any hardware or software issues. I will be explaining how to build a Rails API using examples from Your Galaxy.

First things first, we need to create our API file by typing the following into the terminal:

rails new your_galaxy_api --api

This is creating a new rails file, up to the point you are naming your file e.g your_galaxy_api, but with --api we are removing any features that would not be needed as we are just using it to store and receive any data.

Generating Resources — Good ole’ scaffold.

Next, we need to fill our API with the relevant models, controllers etc. To make things quick and easy, we can use a generator to complete this step:

rails g resource phone title pros cons
rails g resource post title content
rails g resource comment content

This creates a phones, posts and comments model, along with their migration files and empty controllers.

Make sure to run rails db migrate to migrate your files, allowing you to create new instances of each model with their attributes.

CORS

CORS stands for Cross-Origin Resource Sharing which prevents resource sharing from any other origin apart from the origin accessing the resource, e.g http://localhost:3000 will be able to access resources connected with our API however any other origin like http://www.samsung.com would not be able to.

The rails resources generator automatically adds in the gemfile for CORS but it will be commented out. We need to uncomment gem 'rack-cors' and run bundle install. Now to get it working, we need to add the following code in our config/application.rb file, under class Application < Rails::Application:

config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
:headers => :any,
:methods => [:get, :post, :delete, :put, :patch, :options, :head],
:max_age => 0
end
end

Does It Work?

One great way to test it is by adding seed data (this is best to do after migrating files). Seed data allows us to create dummy data which is an initial set of data provided to the database. Start the server by running rails s and it may prompt you to visit http://localhost:3000/ or anything similar to access your json data. If you see it there in json format then we are all good to go 😃.

Cleaning up code

You may notice by using the resource generator, there is code that Rails automatically added within your routes. Be sure to remove any code that you do not use — keep that code clean! 🧼🧽

You can decide which code to keep on and which code to remove depending on which endpoints are appropriate for you.

Take a look at this table with RESTful endpoints (note that it is referring to a todo application):

Table via digitalocean.com

Controllers

We now need to add in controller actions depending on what we will be doing with our API data, e.g. fetching, deleting etc.

# GET /phones
# GET /phones.json
def index
@phones = Phone.all
render json: @phones, :methods => :image_url
end

Here we are getting all phones created, along with their attributes. As we are dealing with JSON data, we have specifically asked the index action to render json.

(:methods => :image_url is fetching the images from the API as I have used active storage to manage uploading and displaying images.) 🖼️

Now you have the power to build Rails APIs, create to your hearts content!

--

--

Milan Parmar

Software Engineer 👨🏽‍💻 | Full Stack Web Development 💻 | Smartphone Tech Enthusiast📱