Building a RESTful API with Rails

Hector P.
The Startup
Published in
6 min readDec 4, 2019

The term API seems magical to an aspiring developer. You hear it thrown around in conversation with seasoned developers, new developers, and everyone in between. It seems as it if it is the wielder and destroyer of worlds with its expansive ability to enrich applications. So, what is it?

An Application Programming Interface (API) is simply code that dictates how external applications communicate with a server-side application. While they existed since the 70s, APIs weren’t as easy to use until Roy Felding’s research made Web APIs the preferred option in the early 2000s.

The most common type of Web API is the RESTful API. RESTful API, in general, seems like a mysterious convention that developers follow in building APIs, but they all have the traits below in common:

  • RESTful Routes
  • Uniform Interface
  • Stateless

RESTful Routes
The verb and path follow the conventions displayed in RESTular to allow clients to perform CRUD functionalities via an API or application on a server.

Uniform Interface
Requests from a browser, a server, a script, or any other app result in the same output (usually JSON if it’s a Web API).

Stateless
The server the API is hosted on does not retain any past information about the type of request a client has made nor the routes a client has accessed.

So, now that we’ve broadly covered the traits of a RESTful API, let’s dive into its magic by creating an API via Rails in 10 steps!

Step 1 is creating a new rails app in your local machine with an API flag. The API flag rails automatically add and remove files (mainly unnecessary Middleware) to help expedite the process of making an API.

Command for creating API rails app without unnecessary middleware.

One of the main differences you’ll notice is the ApplicationController now inherits functionalities from the ActionController::API module. The API module excludes functionalities used primarily by browser applications.

Step 2 is creating your models for your API. We’re going to make a simple API that will allow you to retrieve Celebrity names and their respective Wikipedia page.

Step 3 is running a migration to create the Celebrities table in your SQLite3 database. The generator automatically creates a migration file when you generate a model.

After migrating your table, your schema.rb file will generate.

Step 4 is adding validations to your Celebrity.rb model to ensure the integrity of your API when Creating and Updating new Celebrity objects.

Step 5 is seeding your database with Celebrity names and Wikipedia pages. Otherwise, why would anyone want to use your API? Create Celebrity objects in your seeds.rb file using the syntax below:

Now, for the fun stuff… How should we go about writing the logic for the API? Should the logic be written in the Model layer or the Controller layer? The Controller layer is the mediator between client-side and server-side interactions, so let’s create a Controller for the Celebrity API with a twist.

Step 6 is following RESTful API convention by creating an API folder inside the Controllers folder and create a celebrities_controller.rb file in the API folder.

The real convention is to create a versioned folder within the API folder to enable caching functionality, but I’ve bypassed that convention for brevity’s sake. Sorry!

Step 7 is wrapping the CelebritiesController with the API module to ensure your controller inherits the methods and functionalities to run an API.

Step 8 is creating RESTful Routes for the Celebrities API. In your Config folder, locate the routes.rb file to explicitly write the routes for your API. I elected to create every route using the code below:

Step 9 is building out the Controller actions to allow your API to perform CRUD functionalities on the database. You’ll quickly notice there isn’t much of a difference between the code in a normal Rails app and an API version.

The major difference is each CelebritiesController action renders JSON instead of the traditional embedded Ruby file.

Using “render json:” and the object by itself is sufficient to display data to the client, but it is impossible for the client to know if an issue arose, the type of issue, and the HTTP Status.

Don’t do this.

Please be nice to your fellow developers by including Statuses and Messages in your JSON output, error-handling by appending the .errors method to your object, and HTTP Status codes.

Do this.

Adding this functionality will make a world of a difference when you’re making calls to your API. You will have full context when you view JSON data.

Step 10 is running your Rails server and testing out your newly-made Celebrities API!

Your browser is the best way to test out a GET request to the Celebrities API, but what about POST, PUT, PATCH, or DELETE requests? Fortunately, you can use a tool like Postman to explore every request type.

Click on the dropdown menu in the upper left-hand corner to select the type of request you’d like to make to the API.

  1. Click PATCH if you’d like to change the attribute of existing Celebrity in the database.
  2. Type in the URL of the Celebrity you would like to Edit and Update.
  3. Click Headers to select Content-Type as the Key and application/json as the Value.
  1. Click on Body and the raw option to reveal the text writer below.
  2. Type in the Celebrity attributes and values you would like to change.
  3. Hit the Send button to submit the PATCH request.

You’ll see the following output if the client sent the PATCH request successfully and the Celebrity API processed the PATCH request successfully. Check out your index or show page to see your changes in the browser!

Congrats! You’ve built a basic RESTful API using Rails. After performing the above steps, you’ll see the Celebrities API is a simple Rails app that swaps out embedded Ruby views for JSON data. What would you add to this API to increase its functionality? Feel free to clone the Celebrities API repo and let me know what you would do in the comments below.

Thanks!

Sources:
Architectural Styles and Design of Network-based Software Architectures
Build RESTful API in Rails
REST Constraints for APIs
Rails HTTP Status Codes

--

--

Hector P.
The Startup

Software engineer. Neuroscience, fitness, and music.