Initializing Rails API App

In this blog, we will set up a simple Rails API App from scratch. We won’t be going through building models or controllers here.

Installing Rails

Let’s install rails first, we will be using Rails 5.1 here for example, if you don’t have it run

gem install rails -v '~> 5.1'

And your rails version should be ready

Setting up a Rails API app

To install rails, run the command below it has got flags to skip the parts we won’t need in our project. Run it now we will pick it apart next:

rails new repo-backend -T --skip-spring -C -M -d postgresql --api

Whew! That’s a mouthful. Let’s see about all those switches.

  • -T amounts to skipping the built-in testing framework. We’ll test our API with something other than MiniTest, so let’s drop it for now.
  • --skip-spring removes Spring from our application; that’s a personal preference. If you don’t know what Spring does and whether you should remove it, I urge you to find out and decide for yourself.
  • -C skips Action Cable. No web socket communication for us!
  • -M skips Action Mailer, which wouldn’t be of any use to us.
  • -d postgresql of course, sets us up for the PostgreSQL database.
  • --api - now we’re talking! This runs the Rails generator in the API mode, which sets us up for reading and writing JSON instead of pumping out HTML.

Now we can run tree on this new app, and… wow! When you compare that to a regular Rails app, this is really barebones. But we can trim this up a bit more:

  • An app/jobs directory was generated for us. We know that there will be no jobs in this application for the foreseeable future, so we can drop that.
  • There are four initializers that are commented out by default: backtrace_silencers.rb, application_controller_renderer.rb, inflections.rb and mime_types.rb. We may as well remove those.

One of the initializers will come in handy, though: cors.rb. We can uncomment what is already there and modify it to accept all origins:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins ENV.fetch('ALLOWED_ORIGINS') { '*' }
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete,:options,:head]
end
end

This will make us happy campers in development and allows us to set it properly for production — when we will know where our front-end lives. As a side note, simply allowing * would also be fine if we were going to call our API from e.g. a mobile application.

To use this, we need to uncomment rack-cors in the Gemfile.

Setting up the database

We need to point our Rails app to the instance of PostgreSQL in different environments.

Our database.yml looks like this:

default: &default
adapter: postgresql
encoding: unicode
host: <%= ENV.fetch["db_host"] %>
user: <%= ENV.fetch["db_user"] %>
password: <%= ENV.fetch["db_password"] %>
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000
test:
<<: *default
database: rails_backend_test
development:
<<: *default
database: rails_backend_development
production:
<<: *default
database: <%= ENV['DATABASE_URL'] %>

And our backend is all set, let’s get it running:

bundle install
bundle exec rails db:create
bundle exec rails db:migrate
bundle exec rails s

While working in production mode we need to add a flag RAILS_ENV=production after the command, we need this in commands like while running migrations or rollbacks and to start production server.

e.g.,

bundle exec rails db:migrate RAILS_ENV=production\
bundle exec rails server -e production -p 3002

-p flag to specify the port

If everything went well, our database should be set up!!!

We have successfully set up a rails app from scratch to use as an API application with a PostgreSQL database.
Next, you can work on controllers, models, etc. as per your use cases.

--

--

--

Building influencerbit.com, 📍Bengaluru

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Build a GUI Program with Python

The Static Keyword in C

Steps to create and deploy an Express API on Firebase

Woman stand with a laptop

A Very Quick Explanation of Quick Sort

Getting More Out of Spark

Nebula AI 2021 September& October AMA Report

Raise your hand if you want to quit drinking coffee. Why, though???

FULL STACK WEB DEVELOPMENT

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
Aman Kumar

Aman Kumar

Building influencerbit.com, 📍Bengaluru

More from Medium

Ruby on Rails MVC Framework

How to get & build full URLs in Rails

Ruby on Rails Console

RailsTasker: Rails Automated Post Deployment Tasks

Ruby on Rails post deploy task automation