Setting up a Rails API Backend

Gabriel Valle
8 min readDec 16, 2018

--

The initial intention for this article was to provide a quick guide on setting up a Rails API that I will be using for future articles, but I’ve decided to go into a little more in depth to stick to my goal of providing guides to newer developers that don’t gloss over things that may seem trivial to more experienced developers.

While this guide will walk a reader through creating a Rails API, it does assume the reader has their computer set up for a programming environment. This is not a guide on how to install things like Ruby, Rails, or Postgresql.

To begin creating any Rails application, we need to enter a few commands in the terminal

mkdir list-app
cd list-app
rails new . --api --database=postgresql

Let’s break down these commands

mkdir list-app

This command tells the computer to make a new directory (mkdir) called list-app (this is going to be the name of my application, so this can be changed to whatever you desire.

cd list-app

This command tells the terminal to change to the newly created directory so that future commands will be run in the correct location

rails new . --api --database=postgresql

This is a Rails command that creates the new application in the current directory. The additional options included at the end of the command will create an API version of the Rails application and also assign the database to be postgresql instead of the default mysql. The change in database is important because it makes a future step of deploying to Heroku easier.

Once Rails is finished files and installing its dependency gems, which could take a few minutes, we need to tell the system to create a local database with the commandrake db:create.

Now go ahead and start up the local server by running the command rails s -p 3001. We are running the Rails server on port 3001 instead of the default port to avoid any conflicts down the road when the React components get added.

If you visit http://localhost:3001 and see the below image then everything was setup correctly

Congratulations! You’ve successfully created a Rails API. The rest of this article will be a bit specific to the application that I will be using in future articles, but the concept behind it can be applied to any application.

The next thing to do is uncomment the becrypt gem in the App’s gemfile and then run bundle install in the terminal. This will allow us to provide security for users’ passwords. We also need to reactivate Cookies in order to use the session. There are 4 lines that need to be added to config/application.rb

Also sprockets/railtie needs to be uncommented in the application.rb file

So now the application.rb file should look like

With the Rails API setup, we now need to add some migrations to our application to create our database structure. Let’s start with the migration for our User table. Enter the following command in your terminal rails g migration CreateUsers.

This will generate a new file located in the db/migrate folder. This file should look like

Now we need to add the columns that will be in our users table; I’ll be adding a username, email and password column to my table. This causes the file to look like

The password_digest column is a requirement of our Bcrypt gem, otherwise a simple password column would work. The t.timestamps will create two columns, one that stores the date and time when a new record is created and one that stores the date and time when a record is edited.

Next we need to create a migration for our list table. This table will have a title, a status, and will belong to a user. Our migration file should look like

Lastly we need to create a migration for our list items table. This table will have a name, quantity, status and will belong to a list. Our migration file should look like

With the migration files ready to go, there is one last thing to do before moving on to the next step. Running the following command rake db:migrate will instruct Rails to run the migration files and create the tables and columns in the database.

The next step of creating a Rails API is setting up the models, we will be starting with the User model. Navigate to the model folder, it is nested under the app folder in the root of the directory. In the model folder we need to create a user.rb file to house our User model. In order to have Rails work its magic, each model file will need to contain a class of the same name. The User model file should look like

Line 3 tells Rails to not make a new User unless a username and email is provided. Line 4 tells Rails to make sure the username and email provided are unique before creating a new user. Line 5 is provided by the bcrypt gem and will encode the password provided by the user so it is not stored as a plain string in the database. This is important in case the database ever gets hacked; otherwise, a hacker will have easy access to a user’s email and password and most people reuse the same password on numerous sites. Line 6 informs Rails that there is a relationship between the User and List model and that each User can have many lists.

We will setup our List and ListItem models in the same folder and following the same conventions as when we created our User model. Here is what the list.rb file should look like

and the list_item.rb file

With all the models setup, we are going to move to crafting our controllers so we have CRUD capabilities. We need to create a controller for each of our models, except the User model which is handled slightly differently; these files need to be located in the controller folder that is nested in the app folder in order for Rails magic to be successful. The User model will have two controllers, one to handle users logging in and out, Sessions Controller, and one to handle user registration and account deletion, Registrations Controller. The Sessions and Registrations Controllers will be kept simple for this example because the end result app will only allow users to sign up, log in and log out. Here is what the Sessions Controller should look like

and the Registrations Controller

We need to have our controllers render json instead of HTML since our Rails backend is in API mode.

The ApplicationController needs to be modified slightly. Since we are using session to store user_id upon login, we need to add a way to access the current user in all of our controllers. With all of our controllers inheriting from the ApplicationController, it is the perfect location to house this method. The ApplicationController file should now look like

With our methods to check for the current user, we can not setup our Lists Controller. We want users to be able to see all of their lists, view a specific list, create new lists, update lists and also delete lists. We also don’t want users to be able to do any of those things unless the list belongs to them, so we need to check the current user id vs the user id provided in params before performing an action. This results in the Lists Controller looking like

We need to follow similar logic for our List Items Controller, except we will restrict actions to Create, Update, and Delete. Here is our List Items Controller

With the Controllers setup, we need to add serializers to make parsing through the JSON responses much simpler. First add the gem ‘active_model_serializers’ to the Gemfile and run the command bundle install. Now we need to add a serializer file for each Model, these files need to be located in app/serializers. Each serializer needs to be setup to pass the needed attributes of the corresponding model and also any relationships that need to be accessed when retrieving the JSON response. Here are the three serializer files

With the migrations, models, controllers, and serializers setup, the final step is to construct the routes so our backend knows how to direct traffic and what information to provide when queried. Convention is to have the routes for APIs to be nested under ‘/api’, also we do not want to create routes which lead to dead ends so we need to make sure to restrict which routes are available for each model and there needs to be routes for login, logout and signup. With these guidelines in mind, here is what the routes.rb file should look like

If you’ve followed the article to this point then take a quick moment for some celebration because there was a lot of material covered in this article. If you’ve been coding along then you will have a working Rails API that can be used to create a List tracking application. I will be expanding on this API in future articles using React to build the front-end. Please ask any questions in the comments and I will respond as soon as I am able to.

--

--