Developing an API that works exactly like you intend to and that too all the time is not an easy task. No matter how careful you are, there can always be instances of wrong serialization or incorrect authentication. However, with Rails 5, the story has changed to a great extent.
In this article, we will be looking at the steps that one should take to develop JSON APIs using Rails 5. Let us start with looking into what makes JSON API development the correct business choice, before we move on to the steps of actual development.
There are a number of reasons which makes it beneficial to develop JSON APIs. Here are some of them:
- Most often than not, if you wish to deserialize the custom JSON responses you are supposed to know both - endpoint details and the response contents you just hit. The JSON API resolves this issue by exposing the data type as your responses’ first class data.
- Reading errors automatically is another face that API developers face to a huge extent. In the JSON API, you get a specific error format. It allows your API user to implement own representations of errors, easily.
- In the JSON API, relationships and attributes of every given resource is separate, which expose the data relation in an unobtrusive way. It means that the clients who are not interested in knowing the relationships can make use of the same code for parsing response, with or without the relationships.
- It also allows implementation of backends that can exclude or include the given relationships as and when demanded Doing this makes performance tuning a lot easier.
- In the industry, there is a profound demand for creating the self-descriptive APIs. These are the ones where the client himself can configure all the endpoints by only by following the links that are included in all the API responses.
- The JSON API assist links such as these, thus enabling you to using the HATEOS approach to its full potential.
There is very straight forward distinction between the auxiliary data and the resource-related data that you send in the responses. This makes it easier to not assume wrongly about the scope of response data and the response itself.
Coming to Rails
Rails is best for making the traditional server-based web applications. Rails has the support for sessions, cookies, and a number of other browser-focussed functionalities straight from out the box. It is also deemed ideal for developing the JSON APIs. The match that Rails and JSON API have grown to be, have made the framework an ideal choice of mobile app development company that excels in API development as well.
Now that we know the benefits of developing a JSON API and have established that Rails framework is the right match for the API development, let us now get you started with JSON API development with Rails.
Let us first start with using Rail 5 in the API mode. Here are the steps for that:
- Make sure that you your Ruby version is 2.2 or higher
- Install Rail using the master branch
- It’s time to develop a new Rail API app, which is done by passing the --api directive into the rails new command.
Once you have covered these steps, the next is to respond with JSON: however, before you move ahead with that, we first need to know the right JSON format that you should be using.
Choosing the JSON Format
When we talk about what the JSON format should look like, developers come across a number of questions like - Should you add a root node while responding through multiple objects? Also, what about when you are responding therough single objects? Where should you put in the meta information, and then - how do you embed the related or nested data?
json:api, popularized by the Rails and Ember community, is what the developer community is going with currently as the right JSON format.
The next step is Serializing the JSON responses.
ActiveModel::Serializer, which is already included in your Gemfile helps you define the relation and attribute that you would most likely include in the JSON response. It even acts as presenter in which you can define the custom methods for displaying the extra information or for overriding how it gets displayed in the JSON.
While serializing, there are usually two models - User and RentalUnit. The concept is that RentalUnit belongs to one user and the user can have many RentalUnits.
In the RentalUnit Serializer, we define the attributes which are to be included in the responses, these can be anything which RentalUnit object give a response to. While in the User serializer, we override how the name field gets displayed in a JSON response.
After Serialization, the next step is Caching
Caching is very important when you are working with APIs, especially when the data do not change that often. If you can afford to send across minutes old data to your users, one of the best ways of increasing your website speed would be to use a tool like Varnish Cache, which is a reverse proxy server that serves cached version of the content on the basis of different TLLs.
When you do fragment caching and full object caching with ActiveModel::Serializer (AMS), the time you spend in serializing your objects will lower to a huge extent.
Once you have setup your cache with AMS, the next process is Throttling.
When you develop an interface, you have to pay attention to the number of requests that can be made on your API.
To limit the request made on your API, we make use of the Rack::Attack Middleware.
The middleware allows a number of factors:
- blacklist: Send a denied message for specific requests
- whitelist: Process normally if specific conditions are met
- throttle: Check if user request is inside the allowed usage
- track: Track request to log information about the requests
We'll talk about them in an upcoming article.