Creating a Rails Backend API from Scratch

If you want to create a Rails backend, then this blog post is for you! I’m going to go step by step and show which commands you need to run, files you need to change, etc.

First, we’re going to generate our rails application using the code below. This is going to be a simple application that will list sports and leagues within that sport. We’ll be using postgresql for this example.

rails new sports-api --api -d=postgresql

Go to your gemfile and uncomment gem ‘rack-cors’ and run bundle install.

Afterwards, navigate to config/initializers/cors.rb and uncomment lines 8–16. note: you will need to change line 10 origins: ‘’ to whichever locations you want to access your API from. If you just use an asterisks it will be available everywhere.

Lines 8–16 were uncommented, and line 10 was changed to allow access from anywhere.

Next you will generate resource(s). This app will have two— sports and leagues.

rails g resource Api::V1::Sport name abbreviationrails g resource Api::V1::League name abbreviation sport:references

We will need to fix our migrations. Rename the file, the class name, and the table name to not have API::V1.

the filename and class name were changed by removing api v1

Run rails db:create to create the postgresql database. (This was the point where I had to spend about 20 hours over a weekend figuring out how to get postgres on my Mac. It was very fun.)

Run rails db:migrate to create the tables.

Next, fix your models. You will need to remove the API V1 naming from your models as well. In addition, move the sport.rb and league.rb out of app/models/api/v1 and move it to just app/models. You then delete the folder api.

Also, since League references Sport, we need to update the ActiveRecord association.

Our updated Sport model
Our updated League model
Our updated file structure for app/models

(Optional) Seed your database. I’m going to create two Sports (football and basketball), and two leagues for each sport.

seeds.rb file with sports and leagues

The final step is to update your controllers to render JSON. In this case, I want a JSON to show the sports and all the leagues for that sport in an array.

the index rending json

Voila! Now if everything worked, you can type rails s, navigate to http://localhost:3000/api/v1/sports and the JSON file should appear for you!



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