Building A Rails API

Chris Kakos
The Startup
Published in
8 min readMay 12, 2020

A n Application Programming Interface defines the interaction between multiple software intermediaries, or so says Wikipedia. For someone with experience in building or interacting with APIs this is a precise description, although it may come across rather vague to anyone who is just now beginning to learn. This is because an API can take shape in different forms, but at its core is nothing more than the intersection of where one system communicates with data from another system.

Picture this. You’ve had a tough week. Normally you would concede to sitting on the couch and eating ice cream while binging shows that no one else watches, but not tonight. Tonight is different. You decide to gather an ensemble of co-workers, lower all inhibitions and throw caution to the wind by toasting the town. At the moment, you are having the time of your life. Snapping pictures at an unprecedented rate to commemorate this auspicious occasion. That is until the following morning.

I n the wake of it all, you aguishly regret going out the night before. There’s melted chocolate on your bed sheets, your head is pounding and you can’t seem to locate your other sock. After stumbling a few times en route to the couch, you decide to look through your photos for a recap of events. Yikes. The first photo is a not so flattering portrayal of you humping a historical landmark in the center of town. As you swipe along, you find a friend so graciously documented a bouncer escorting you out of an establishment, hanging from his right shoulder. It gets worse. You toss your phone to the ground in disbelief. Luckily, you hadn’t posted anything online. You can now consciously select which photos are appropriate enough to showcase your antics from the previous night, on the social media platform of your choice.

Although extremely far fetched and drawn out, this scenario comparatively illustrates how an Application Programming Interface is built. An API is essentially a selection of data made accessible for developers to interact with when building applications. If you’re still not sure what I am talking about, it’s not your fault. I blame myself. Stay on course as we build and see if that helps to make sense of it all.

courtesy of Eucalyp of thenounproject.com

Why Rails?

Rails does a lot of things well. This being one of them. With prior understanding of the MVC architecture and CRUD functionality, building a Rails API is a quick way to get something into production in a limited amount of time. This article merely demonstrates the basics of getting you up and running, so for a deeper understanding and options feel free to check out the official documentation.

There are a multitude of ways to build an API. Today I’m using Rails but If you’re into JavaScript, you could use NodeJS just the same. Python developers use frameworks like Flask or DJango, PHP uses Laravel and newer technologies like Elixir with Phoenix are gaining traction. The point isn’t to overwhelm you by the amount of choices but to be aware of the options available. The most important part when you’re first starting to learn is to pick a language that feels the most comfortable and go from there.

Getting Started

First we need to create the Rails API file structure. Open a terminal and run the following command:

$ rails new mario-bros-api --api

the - -api flag limits the amount of files that would normally generate, essentially creating a more API-like file structure.

Installing Gems

Next we’ll add some gems. I will explain each in more depth as we approach them in the process. For now, add the following gems inside of the Gemfile:

Gemfile

Then run the bundle install command in your terminal:

$ bundle install

Generate Resources and Migrate Table

Let’s generate resources for the characters table and migrate it to the database:

$ rails g resource Character name catchphrase secret_key

$ rails db:migrate

the resource command will generate my model and controller as well as my CRUD routes to the appropriate directories. We’ll see that shortly.

db/schema.rb

Controller Configurations

Now let’s add some CRUD functionality by configuring the index, show and create actions in the characters controller. I will also provide two private methods: One named character_params which will contain the required attributes for creating an instance of a Character. As well as a method named find_character for searching an instance of an existing Character.

Normally you would render a view file when an action is requested. Since we are building an API, you have to render instance variables to JSON format. I also included a status code of 200 upon each render to notify the browser that the request was successful.

Serializers

Serialization is the process of translating data structures or object state into a format that can be stored — in a file or memory buffer — or transmitted — across a network — and reconstructed later. The most popular form of serialization is JavaScript Object Notation (JSON) and it’s used to make data exchange easier and faster to transmit.

A Serializer converts your models into JSON format and allows for the customization of whichever attributes you wish to render accessible by anyone making requests to it.

Earlier we installed some gems. One of which being active_model_serializers. Seeing how Active Model is a part of the Rails ecosystem, I’m going to use Active Model Serializers for this demo.

Serializers are not specific to Rails architecture. There are others at your disposal, such as Fast JSON API which was built by Netflix. Developers use Fast JSON API because it is highly customizable and super fast. Netflix uses it to transmit over a petabyte of data to its users, so if it’s good enough for the leading streaming service in the world, it should be good enough to support your Pet Finder App. Burn.

Look inside of the appdirectory and check to see if there is a folder named serializers. If there is already a serializers folder present, then you can skip this step.

If there isn’t, generate one a by running the following in your terminal:

$ rails g serializer Character

app/serializers/character_serializer.rb

This is where you specify which attributes you’d like to make publicly accessible. Notice in the schema.rb file, the Character Model has three attributes: name, catchphrase and secret_key. Only the attributes specified in the serializer will be available when the API is up and running, so leaving out an attribute named secret_key is probably a good idea.

We’re not going to be using the secret_key attribute but I wanted to include it as an example of how to use a serializer to customize the data you wish to make public. Keep in mind that if you needed to authenticate a User, a secret_key might be a good place to do that but you wouldn’t want to make that kind of sensitive information accessible to developers interacting with your API.

Also, If you had an Associated Modelshameless plug to a previous article that I wrote — in relation to Characters, you could add that relationship in your serializer to make that data accessible as well.

Seeding Database

Add some seed data to work with in order to test if the API is working properly. You can do this one of two ways:

  1. Create instances in your db/seeds.rb file and run $ rails db:seed from your terminal.
  2. Run $ rails c from your terminal and create your instances inside of the Rails console.

Once your database is seeded, run the server:

$ rails s -p 3000

And go to localhost:3000/characters in your browser:

localhost:3000/characters

It’s Alive!

How cool is that? And let’s be honest, that was fairly quick. Certainly we aren’t dealing with the most sensitive data but we’re here. Now we just need to find parking…

Cross Origin Resource Sharing

CORS is a mechanism that allows restricted resources on a web page to be requested from another domain outside from which the first resource was served. In other words, CORS acts as a gatekeeper of sorts to only allow whatever resources specified, access to interact with your data. Rails uses a middleware called Rack::Cors to facilitate this process. The second of the two gems that we installed earlier.

config/initializers/cors.rb

By enabling this middleware, client-side applications will now be able to make requests to your data. Seeing how I’ve been writing my fair share of JavaScript as of late, I am working on writing a continuation of this piece to demonstrate how a client-side application interacts with our newly built API.

Summary

What a day! If you’re rendering JSON with your uniquely seeded data, I salute you. If not, then this is a great time to learn how to debug.

Let’s Recap what we did:

  1. Create new rails app with -api flag.
  2. Generate resources and migrate tables to database.
  3. Install rack-corsand active_model_serializer gems and bundle install.
  4. Configure CRUD actions in your controllers and render JSON formatted data.
  5. Generate serializer for your models and specify the attributes you wish to make public.
  6. Seed the database.
  7. Enable rack-cors middlware.
  8. Start the server and visit localhost:3000/characters in your browser.

APIs are a very popular tool in modern web development. Because of this, learning how to build them will only contribute to a deeper understanding of how to interact with one. The API we built is very bare bones. Make sure to play around and refactor some code. Maybe add an ActiveRecord Associationanother shameless plug — to Character and see how the JSON changes upon refresh.

I’ll be right back.

--

--

Chris Kakos
The Startup

Software developer skilled in ecosystems surrounding JavaScript.