DEV Community

Cover image for How To: Create a Rails Backend API
Adriana DiPietro
Adriana DiPietro

Posted on

How To: Create a Rails Backend API

Hi there!

Today, we will be walking through how to create a Rails backend API utilizing a postgresql database. This will be a simple way to start a project that may be complex!

🌞 Let's get started 🌞

Creating a project directory

In your base directory of your terminal, you can create a project directory using this command:

mkdir project_name_here

Look! First step already done. Now, let's change directories so that we will be inside the project. Input this into the terminal:

cd project_name_here

Cool! Let's move onto the good stuff...

Generating a Rails backend

While remaining in your project directory, we are going to generate the Rails application using:

rails new project_backend_name_here --api --database=postgresql

Toward the end of our command, we "flag" an api and "flag" a postgresql-based database. These two flags will help us to create and store data.

Now if you open your code editor, you should see something like this:
Screen Shot 2021-08-16 at 8.36.36 PM

Using the "rails new" generator gave us a ton of stuff. Our backend includes, most notably:

  • an "app" folder that houses our Model-View-Controller (MVC) structure.
  • a "db" folder that houses our database migrations, schema, and seed file.
  • a "config" folder that houses a routes file, environment file, and initializers folder, etc.

Creating & Migrating a Database

Next, we can go to our terminal and run:

rails db:create

Simply, this creates our database. From here, you can now start creating migrations.

Command lines like ⤵️ will generate a whole MVC structure for that resource.

rails g resource User name, email, password

Whereas, command lines like ⤵️ will only generate the model structure.

rails g model User name, email, password

Or, command lines like ⤵️ will only generate the controller structure.

rails g controller User

Whatever you may choose, always migrate after each created migration. We can do this using:

rails db:migrate

This will ultimately finalize your migrations and set up your schema.

From here, you may add seed data, add many more resources, install gems... the list can go on forever.

While this may be an oversimplified explanation of creating a Rails backend API, I find it necessary indulge in. Everyone has a starting point to their education and career in tech, so why not help?

🌞Feel free to comment below!
🌞Feedback + questions are welcome.
🌞As always, let's learn together<3

Top comments (3)

Collapse
 
ioskpu profile image
ioskpu

You are great Adriana.. thk

Collapse
 
am20dipi profile image
Adriana DiPietro

Thanks for commenting!

Collapse
 
noloman profile image
Manuel

if we're just creating an API app, do we still need to generate rails g resource User name, email, password? or would it be enough with the model?
Thanks!