How to make your first API with Ruby on Rails

Let’s start with the basic building block that you need to understand. API stands for Application Programming Interface, and it is a way to make different applications built by different teams to share information between them. It will help your applications get information that otherwise you would have to code yourself. The most common example is weather information for your page, but there is an API for any information you may need. Some companies like Amazon are built based on APIs so not only their entire system can communicate, but also share some parts of their data with an external application made by any developer to integrate their ecosystem into different solutions.

Photo by Med Badr Chemmaoui on Unsplash

All APIs will have their documentation, where the creator explains how to use it and integrate it into your application, specifying the format you should expect the response, the parameters that the request must-have, and the authorization and authentication methods for its use.

Most of them are built with a philosophy called CRUD, which uses an HTTP request to access and use data. The request must use one of the HTTP methods to communicate with the API and allows the users to perform different actions on the data: Create(POST), Read(GET), Update(PUT or PATCH), and Destroy(DELETE).

Photo by kira cheng on Unsplash

Now that we have an idea of what an API is and how it works, it is time for us to do our API using Ruby on Rails. From Rails 5 and up, support API only was added, making the configuration and implementation so much faster by eliminating functionalities that would be unused.

Before we start, make sure that you have the correct versions of ruby(above 2.2) and rails(5 or above) by running the following commands in the terminal:

$ ruby -v

If they are not up to date you must make the update before moving on. For information on installing rails, you can check here, to learn how to install rails go here, and how to update ruby go here.

Like with any rails application you should make the design of the whole API first so you know exactly what models you are going to need and what are the associations between them. My recommendation is to make an ERD, to avoid any confusion through the making of the API. Once you have your models decided, it is time to select which information you are going to let users manipulate and how.

To access different data, the APIs use something called an endpoint, it is just a specific URL that lets you interact with a section of the data. Now that we know how to access the data it’s time to define the different endpoint and their respective methods to manipulate the data. Remember that the same endpoint can do different things depending on the HTTP method that you make the request with. With this information, it’s recommended that each model should have its own endpoint and add additional endpoints for special cases.

To create the API project, rails has the following command that you have to run in the terminal:

$ rails new MY-APP-NAME --api -T

For this command, the - -api argument will create the application with API configuration, and the -T argument is to tell rails to skip the minitest as the default testing environment because we are going to use RSpec as the testing framework for the project.

To add Rspec to the project just add the rspec-rails gem to the gemfile in the development and test sections, and run bundle install to install have it in the project.

After those steps are done, we will initialize RSpec so every time we add something to the project the tests are automatically generated as well. Run the following commands in the root folder for the project:

$ mkdir spec

This will add the .rspec configuration file in the root folder and the rails and spec helpers in the spec folder. Congratulations, RSpec is ready to go.

Photo by Jingda Chen on Unsplash

Now it is time to create the models that our API is going to use. We are going to generate everything at once using the scaffolding functionality from rails.

$ rails generate scaffold MODEL-NAME field-one:type field-two:type……

This command will generate the model, migration, controllers, and tests all at once for you to modify and configure with the functionality that you need.

After this, it is pretty much like any other rails application. You must define the associations between models that you already have in your ERD and check the data that the controllers are getting and returning to the user.

If additional endpoints have to be created you can do it in the routes.rb file in the config folder. In that file you can define the method for the endpoint and the controller that is going to be handling it:

get ‘/login’, to: ‘users#login’

This specific example shows an endpoint called login that responds to the GET method in the HTTP request, and the controller that is going to be sent to is the user controller and the login method of that controller. For this example, we used the get method but you can use any of the other methods. To learn more about custom routes you can go to the official documentation.

Every request should have a response code associated with it, so the other application knows what to do with that response. When you create data in Rails, the response sent by default is code 201, which means created, but you can modify the response to have the code that you need. When you are rendering the response in the controllers just add the status property to that response with the code number or name that you want to send.

render response: 'Not authorized', status: 403
Photo by Malachi Brooks on Unsplash

One last gem that has to be installed for the API to work with any requests coming from any site, is the rack-cors gem. This gem should be commented in the generated gem file but if it is not there you should add it to the general gems section. After it is installed you have to configure it, check the last version of the gem from rubygems.org, and the documentation posted to see the latest configuration needed for it to work. As of the writing of this article, the latest version is 1.1.1 and the configuration is made in the config/application.rb file by pasting the following code and adding the methods you need for your specific API.

module YourApp

After all this you should be all set with your API, the only thing left is to deploy it and test it with tools like postman to see if it is working as intended.

In this article, we learned that making an API is very similar to creating a Rails app but your user is going to be non-human this time, and the responses are different from those you are used to, but with a little practice you can make a very strong API fast and easy with the help of rails.

Photo by Alasdair Elmes on Unsplash

Big thanks to digital ocean, from where the majority of this article was taken check it here if you want to follow their tutorial, and thank you for reading the article all the way to the end. I hope it was helpful and wish you good luck with your projects.

Electronic engineer and software developer

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