DEV Community


Creating a Ruby on Rails API Back-End

Dev. I love dogs, cookies, and learning new things.
Originally published at ・5 min read

Ruby on Rails is a framework for building web applications using the Ruby programming language. While it can be used to create a complete website, it can also be used to create an API back-end for a React-Redux front-end, as is required for my final Flatiron project.

To Start

Begin by creating a Rails app as you normally would, with the addition of “--api” and “-T” as below:

rails new app_name --api -T
Enter fullscreen mode Exit fullscreen mode

The addition of “--api” will create an app with “a more limited set of middleware than normal.” It will utilize ActionController::API in lieu of ActionController::Base, leaving “out any Action Controller modules that provide functionalities primarily used by browser applications.” Your app will also be created without what you would need for a front-end, such as views, helpers, and assets.

The “-T” flag will create your app without the boilerplate test files.

Models and Migrations

You will need to create both your models and migrations, setting up the database that will be used to store and manage the data you’re being sent from the front-end of your application.

Migrations are the files used to manipulate the database schema – they say what your tables are and what attributes they have. After your schema.db file has been created, you can make changes by creating a migration file to add, rename, change, or remove columns.

Models are the files that manage the relationships between your database tables. You can also specify certain validations so bad data is not saved to your database. Models are also the only file that uses the singular name of the table – for example, a model would be User but the controller would be Users.

By using the command line Rails generator for models, you can create both the migration and model files at once.

rails generate model_name column:type columntwo:type 
Enter fullscreen mode Exit fullscreen mode

Check your migration file and make sure it has the appropriate columns and column types. Inside your model file, define the relationships between your tables (has_many, belongs_to, etc.), and add any validations you need.

To bring your database into being, you need to “run your migrations.” If you’re in Rails 5, type the below in the terminal and hit enter:

rails db:migrate 
Enter fullscreen mode Exit fullscreen mode

You should see your tables created and your schema.db file appear. At this point, check your schema file to make sure the tables and their columns are set up the way you intended, so you can make any changes needed.


Your controller files are the “C” in the Model-View-Controller structure. Models are discussed above, and what would be handled by views will be taken care of by your front-end. The controllers handle HTTP requests (GET, POST, DELETE) and return the appropriate information. They are named so as to follow RESTful conventions.

The methods in the controller are called actions and each action is named for a CRUD operation: new, index, show, create, update, destroy.

Because you are not utilizing rails for the front-end, you do not need to use instance variables (@) in your methods. For example, inside index, you can put “class = Class.all” rather than “@class = Class.all”.

To utilize Rails as your API backend, you need to tell each method to render its data as JSON information, rather than rendering views as you would for a full Rails application. For example:

def index  
  class = Class.all 
  render json: class 
Enter fullscreen mode Exit fullscreen mode


Routes are located in config/routes.rb - this is where you specify what actions you are connecting. Index? Show? All of them? The syntax follows:

resources :class, only: [:action, action] 
resources :class2 
Enter fullscreen mode Exit fullscreen mode

To declare all of the common routes and move on, you need only declare “resources :class”

Notes re: the User

If your user should be able to log in, log out, and have a secure password, there are several additional things you will need to do.

In your gemfile, you will need to add, or uncomment, bcrypt. This will allow you to utilize its hash algorithm to handle and store your users passwords safely.

In your controller, for the methods get_current_user, log_in, and log_out, you will need to utilize sessions. A “session” is what lets a website keep track of a user as they navigate the website and when a page reloads. Various syntax examples and tutorials are available online. A dedicated sessions controller will help with the separation of concerns and readability of your code.

In your model, you need to specify that your user has_secure_password.


Your Rails API will need to communicate with your React-Redux front-end while each is running on a different server. Rack-Cors is a gem that lets you easily configure this. CORS stands for Cross-Origin Resource Sharing, a standard that lets developers specify who can access the assets on a server and what HTTP requests are accepted. A restrictive same-origin policy would prevent your Rails API at localhost:3001 from sending and receiving data to your front-end at localhost:3000.

Add rack-cors to your gemfile (gem ‘rack-cors’) and then run bundle. For Rails 5 applications, add the below to your config/application.rb file:

config.middleware.insert_before 0, Rack::Cors do 
  allow do 
    origins ‘*’  
    resource ‘*’, headers: :any, methods: [:get, :post, :options] 
Enter fullscreen mode Exit fullscreen mode

By default, that language allows the specified HTTP requests (get, post, etc.) “from any origin on any resource.” If you wish to be more restrictive, or allow different HTTP requests, you will need to make those changes. For this project, add :put and :delete to the allowed methods.

Updating the port Rails uses

When working on your front-end, you’ll want to have both the client and the API up and running, and they’ll need to be at two different ports. Inside config/puma.rb, look for “port ENV.fetch(“PORT”) ” and change that number to 3001. React-Redux will be defaulted to localhost:3000 and your Rails API will be up on localhost:3001.

This should be enough to have your API up and running and ready for use with your front-end. EXCITING.

Discussion (0)