Ruby on Rails
Note: This blog is aimed towards people with some experience making Rails applications
For the first six weeks, we had been focusing on creating web applications completely within the confines of Rails, using ERB templating to actually embed Ruby code into our front-end. Now that I think about it, this approach is fine for small projects, but as your application grows you probably want to separate the concerns of the back-end and the front-end. This is where building a Rails API to communicate with your front-end comes in.
6 Alternatives to the Yahoo Finance API | Data Driven Investor
The Yahoo Finance API has long been a reliable tool for many of the data-driven investors. Many have relied on their…
So buckle up and get comfortable, because in this post I’m going to take you from what an API is, to creating a basic Rails API that’s set up to talk to a front-end!
What is an API anyways?
Before we start talking about how to go about creating a Rails API, we must first describe what an API is, what it does, and why it makes sense to use one!
Mike Kail, CTO at Everest, described an API as follows:
“The simple definition of API is that it is a URL or set of URLs that expose a service for customers to programmatically access to send and receive information. This allows developers to connect different systems, or components of a system, without having to understand all of the complexity involved.” — Mike Kail
The implications of separating an application into separate parts — a ‘front end’ and a ‘back-end’, are huge! Separation allows developers to be able to work on one section without having to understand the inner workings of another. This alone is a huge reason for building an API!
MVC Architecture and a Rails API
So now that we know the what and why of API, let’s examine how you would actually implement this. The good news is, if you’ve built a Rails project before, you already know about 90% of the process! I’ll explain. Let’s take a standard MVC structure, we’ve got:
- Models: This is where you describe your classes and the overall logic of your application.
- Controller: The controller is the liaison between your models and your views, sending info from the app to the browser and vice-versa.
Starting from scratch, let’s build a book-list API
We’ll be using generators in this walkthrough because that’s part of what makes Rails awesome. Let’s begin making our application. The premise for the app is a book-list API, that has various books, with their authors, and different genres. A book belongs to an author and belongs to a genre. An author has many books, has many genres through books, and a genre has many books and has many authors through books.
The first step is to generate our new Rails API skeleton using the ‘– –api’ tag. This tag tells Rails to leave out some of the middleware that your application won’t need, and it also makes ApplicationController inherit from ::API rather than ::Base. If this doesn’t make sense to you right now, that’s alright! But for further understanding, check out this in-depth guide.
rails new book-list-api --api
After this, Rails will generate a file structure for you.
Making our Models, Migrations, and Controllers
Rails makes it easy and fast to build out applications!
With the amazing rails g resource command, we can not only build our models but also build the associated migrations and controllers to go with it! So let’s get our story straight first:
- An author: has many books, has many genres through books.
- A genre: has many books, has many authors through books.
- A book: belongs to a genre, and belongs to an author.
So it looks like we have 3 models, and the book is our joining model/table. We have here a many-to-many relationship!
Let’s go ahead and generate! Type the following into your terminal inside of your book-list-api file.
rails g resource author name
rails g resource genre name
rails g resource book author:references genre:references
After running this, your file tree should look like this:
Now that we’ve created our basics, we still have to go into the author model and genre model and code those relationships! It should look like this:
We also can’t forget to check our migration files, so let’s look now.
Looks great! Our books table has our author and genre foreign keys, which is exactly what we want. Now that this is set up, let’s run our migration!
This command creates our tables, and also our schema.rb file! Check out our beautiful schema:
We’re almost there, now we need to seed our database to test and make sure everything works.
Seeding the Database
In our seeds.rb, let’s create some authors, books, and genres!
After you save, run rails db:seed in the terminal.
Now, if that was successful we can check if our associations are made and our database is successfully setup! In the Rails console, type Book.all and you should see:
We’re so close now! All we have to do is go into our controllers and define the actions we want!
Final Steps: The Controllers
In our books_controller.rb, let’s define our index of books! This way we’ll actually be able to access the JSON file containing all our books and their associated authors and genres!
Adding include: [:author, :genre] lets Rails know that you want it to render the associated author and genre information in the JSON, and that's it! We’ve done it! We’ve completed our Rails API. Great job!
Let’s run our local server and go check it out! Run rails server in the console, then open up a browser and go to “localhost:3000/books”. Here we have the books we made! Check it out!
From here, you can build out your front-end and fetch data back and forth from the backend that you built. This concludes the tutorial, but it’s still a very basic API, continue to mess around and add features to see what else you can do with APIs! Happy coding!