Beginner’s Guide to Building a Rails API

Koray Ozkal
Oct 23 · 7 min read

Building an API from scratch for a web application might sound challenging for a first-timer. But if you have the fundamental Ruby on Rails knowledge, you might even find it easier than you expected.

Image for post
Image for post

What is an API ?

Rails can serve as both the front-end and back-end of a website. It can also be configured specifically to work just as an API. So what is an API? Basically, API(Application Programming Interface) is a way for one system to communicate with other external systems. As perfectly explained on Ruby on Rails guides, when people say they use Rails as an “API”, it means developers are using Rails to build a back-end that is shared between their web application and other native applications. The reason most developer use Rails is that it provides a set of defaults that allows us to get up and running quickly. That is why instead of using Rails to generate view files that communicates with the server through forms and links, many developers are treating their web application as just an API client that responds with JSON. So when we are following principles to build an M-V-C structure (Model-View-Controller), rails is only in charge of our models and controllers.

So how we can start setting up our Rails API? Currently, I am working on a JavaScript project at Flatiron school where we are tasked to set our back-end with Rails API and I will code along with each step with you as the article continues to create an API-only Rails build from scratch.

STEP 1 — CREATE A NEW RAILS APP AS AN API

First and foremost we need set up our new Rails app environment by flagging it as an API. Now on your terminal you can follow the format below.

Have you noticed the api flag we used to specify this is just an API?

You may ask the reason. Remember, we mentioned Rails will only used for our models and controller. Therefore, --api flag will allow Rails to remove a lot of default features and middleware that will not be needed. Now controllers will inherit from ActionController::API instead of ActionController::Base and generators will not create views.

I am building a comicbook app to list my comicbook collection so let’s start my app setup

Also I would like to share a helpful tip I came across while watching project built videos: If you are planning to deploy your app to an environment like Heroku, the best practise is to generate a new rails project using Postgresql as the database.(Make sure to download and run Postgres on your computer.)

STEP 2— Configure CORS to allow frontend to make requests

CORS is designed to prevent scripts like fetch() from one origin accessing a resource from a different origin unless that resource specifically states that it expects to share. However, while working on our API, we want to have our Rails server running while trying out s endpoints using fetch(). By using the api flag, the Gemfile was altered to include the rack-cors gem which is commented out initially. So let’s go ahead and uncomment our rack-cours gem in our Gems.

We can now go back to our terminal and run bundle install.

In order to get rack-cors working, once the gem is installed, we need to uncomment the following code in config/initializers/cors.rb file .

Rails provides the cors.rb file specifically for defining our rules for cross-origin HTTP requests.New rails app comes with the string “example.com” . The string after origins specifies which hosts will be allowed to make requests to your API. Now we need to change it to “*” to allow all hosts for our simple Rails API.

Image for post
Image for post

STEP 3— Planning Models

Now, let’s plan our Models. For my Comicbook app, I want to build two models. First one is a Comicbook model that belongs_to a :publisher and a Publisher model that has_many :comicbooks with the attributes below:

Comicbook — has a title, number, artist, writer, image_url so we can add covers and a description.

Publisher — has only a name

Now we can start using rails generator to create our models. If you would like to have a cheatsheet to check how you can build a rails generator, you can also check my previous blog here => RUBY ON RAILS GENERATORS: HOW TO GET YOUR APP UP AND RUNNING & START A NEW RAILS PROJECT .

STEP 3 — Generate Models and Create Database

I will go ahead and type the generators below to my terminal. rails will default to string if we don't specify a type for our attributes.

Then we have to run rails db:create && rails db:migrate

This will create two migrations and two models and with minimal seed data we could even test if everything is working as expected!

STEP 4 — Create Seed Data and Test your associations

Now let’s go to our seeds file db/seeds.rb and create publishers and some comicbooks to start with.

Now we can test the associations on our rails console by typing rails c

Yay!!!!

STEP 5— Generate Controllers

We have our migrations and models set so let’s create our controllers.

We can create all the actions we want. So as an example I would like to build an index action for our app/controllers/comicbooks_controller.rb

STEP 6 — Create Routes

Ok, we are almost there! Let’s go to config/routes.rb and set up our route for the index action.

STEP 7— Test it!

After we complete rest of the controller actions and related routes we can go ahead and run our rails server by simply typing rails sand go to localhost:3000/comicbookson our browser we will be able to see our API in action! Yes we made it!!

Image for post
Image for post
Image for post
Image for post

As a Flatiron School student, writing this article really helped me to learn and have a systematic approach to set up my Rails Api. I am looking forward to building more complex API’s in the future. Happy coding and please let me know if you have any comments or suggestions!

Resources:

https://medium.com/@korayozkal/ruby-on-rails-generators-how-to-get-your-app-up-and-running-start-a-new-rails-project-84e9cefc2c3d

The Startup

Medium's largest active publication, followed by +730K people. Follow to join our community.

Koray Ozkal

Written by

Aspiring Software Engineer, Marketing Strategist -experience with top tech. companies inc. Cisco, Citrix, Hitachi, Apple, Facebook-former NBA writer & guitarist

The Startup

Medium's largest active publication, followed by +730K people. Follow to join our community.

Koray Ozkal

Written by

Aspiring Software Engineer, Marketing Strategist -experience with top tech. companies inc. Cisco, Citrix, Hitachi, Apple, Facebook-former NBA writer & guitarist

The Startup

Medium's largest active publication, followed by +730K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store