Integrating a Third Party API with Rails 5

Ana Gonçalves
Runtime Revolution
Published in
6 min readAug 24, 2017

--

Photo by Dennis Kummer on Unsplash

Sometimes you have an idea for an application but don’t want the hassle of collecting the data you need, or perhaps you need a service to complement your existing app. Whatever reason it might be, sometimes you just need to integrate a third party API. I will show you a quick and easy example on how to use an API to populate the app with some useful data. Let’s get to it!

Setup the API

I really like cooking so I decided to build a recipe app for this. I will be using the Spoonacular API which is available through Mashape. The API documentation is available at this link. In order to setup the API, we will need the API token that’s given to our mashape’s account.

After creating our app, we need to add some gems to the Gemfile. We need dotenv-rails, to keep the API token as an environment variable, and faraday to make requests to Spoonacular API.

gem 'dotenv-rails'
gem 'faraday'

In order to establish the connection and make requests to the third party API, I have created two classes, Connection and Request, under lib/spoonacular folder. This is a fairly simple code for now. Here is what they look like:

In the Connection class, I added the API base URL and the configuration necessary to create a Faraday connection with our base URL and API token.

The Request class will then be responsible for making the actual requests to Spoonacular API. At this point, we’re ready to create the classes we need to populate our app with some recipes.

Processing Data

We now have what we need to make requests to the Spoonacular API. After studying the API, we can design the class structure for the data that we need to represent. This application will only list a few recipes and show their details. So, in this case, we have recipes and a recipe has multiple ingredients and instructions.

For starters, let’s create a Spoonacular::Base class with an attribute errors and the initialization method that’s common to all the spoonacular classes we will create. I recommend that all classes be created under app/services/spoonacular folder, but the organization is up to you.

Spoonacular::Base

After checking the Spoonacular API once again, we will need two specific endpoints, one for the recipes list and another one for the recipe details:

GET recipes/random
GET recipes/:id/information

As you are no doubt expecting, we will now create the Spoonacular::Recipe class which, as previously mentioned, inherits from Spoonacular::Base. This class will have random and find methods that will use Request class to make these two requests. We will also need to override the initialization method, in order to parse the ingredients and instructions that come in the HTTP response.

Let’s take a look at the code:

Spoonacular::Recipe

As you can see, for each recipe that comes in the response a Spoonacular::Recipe object is created. Also several Spoonacular::Ingredient and Spoonacular::Instruction objects are created and kept in the recipe attributes. The code for these last two classes is pretty straightforward, since we just want to store the data.

Spoonacular::Ingredient
Spoonacular::Instruction

Note: we’re not covering requests other than GET, but take a look at Faraday documentation for more information.

Building the Application

We’re ready to build our interface. As mentioned before, this interface will have the recipes list and the recipe details. Therefore, it should not be hard to guess that we need to implement index and show for RecipesController:

I kept the page layout and styling pretty simple, basically added a few options to the menu and some icons to visually categorize the recipes. Since it is not the scope of this article, I’ll not cover the markup and styling, but you can take a look at the final result here. (Note: if you want to run the application, you’ll have to add the .env file with the mashape key)

In case you’re interested in organizing your CSS and you’re missing some tips, at Runtime Revolution we have an article that covers that. You can check it out in the link below. In this tutorial, for example, I’m using SUIT CSS as a naming convention.

Here’s what the application looks like:

Home Page
Recipe Page

Adding Cache

In some cases you might be interested in adding cache to your API requests. Mashaple does have a pricing table that limits the request quota per month, but sometimes you might want to improve the application response time. Either way, there’s multiple reasons to justify adding cache to our system. In this case, we want to avoid unnecessary requests to Spoonacular API, since it can become pricier.

Looking at the final result of the application, I can think of two ways of minimizing the number of requests made. The obvious one is the recipe information endpoint. Once we have the recipe data, it will not change frequently, so we can assume that we won’t need to request this endpoint every time the recipe page is accessed.

I’m also thinking about adding a refresh button on the home page. This way we can cache the recipes list and clean it up whenever the user wants to.

We will then have to make some changes to the method get_json from Request class. Using ActiveSupport::Cache::Store we can store the requests response using the endpoint as key. See the example below:

Rails.cache.fetch("recipes/random", expires_in: 7.days, force: false) do
/* make request */
end

Here’s the changes to request.rb, recipe.rb and recipes_controller.rb:

request.rb
Spoonacular::Recipe
Recipes Controller

Testing

I did not add tests to the code base, but it is good practice to add a couple of them. In case you’re interested in learning about tests around third party APIs, we have a couple of articles that cover this subject. Check them out:

That will be all folks. Obviously this is a really simple example, but I think it is enough to get the gist of it. I hope this will help you to get started and work on awesome stuff!

Have a nice day!

Recommended links

Summary of recommended links throughout the article and some more:

  1. Mashape
  2. Spoonacular API
  3. Faraday
  4. A simple trick to make your classes easier to test
  5. Unit testing with VCR
  6. Organize Your CSS with BEM
  7. SUIT CSS

If you have any comments, questions or suggestions, I’d love to hear them. Let me know if you found this article useful, or if you have any tips on working with third party APIs.

I am currently working at Runtime Revolution. We are a team of developers that work from sunny Lisbon to everywhere. We focus on delivering and maintaining the best possible products to our clients, while having fun, learning and helping each other.

--

--