Table of contents
1.
Introduction
2.
Steps to use External APIs in Ruby on Rails App
2.1.
Installation
2.2.
Creating the database migration
2.3.
Iterating and Seeding
3.
Versions
4.
Kitten API
4.1.
Output
5.
Flicker API
6.
Restful external APIs in ruby on rails
7.
Frequently Asked Questions
7.1.
What do Rails serializers do?
7.2.
Which is better, Ruby or Ruby on Rails?
7.3.
Describe the REST API service.
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

Working with external APIs in Ruby on Rails

Author Ashish Sharma
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will discuss working with external APIs in ruby on rails ruby on rails, the introduction to ruby external APIs in ruby on rails, steps to install the rest-client gem, its installation, creation of database, iteration, and seeding, versions, and restful APIs. Making your application with an API is quite simple, but what about collecting data from other APIs on the internet? Due to the fact that they are all unique and you must authenticate yourself, that is normally when things become a little more difficult.

Most well-known services provide APIs so that programmers can interact with them (they love it if you can get more people using their platform). Airbnb, Facebook, Twitter, Instagram, Flickr, Dropbox... They all possess APIs. You may access their developer's area by just searching for "company X API docs" on Google.

Steps to use External APIs in Ruby on Rails App

Installation

  • Adding the file
     
gem 'rest-client', '~> 2.1'
You can also try this code with Online Ruby Compiler
Run Code

 

  • In your Terminal command line, install the gem with this:
     
gem install rest-client
You can also try this code with Online Ruby Compiler
Run Code

Creating the database migration

Creating the database table now for working on the external APIs in ruby on rails, with all the properties we'll need for our seed. I'll quickly construct a scaffold with the columns I need for this example, which is the campsite name and the campsite reservation URL.

rails g scaffold Campsite name:string url:string
rails db:migrate
You can also try this code with Online Ruby Compiler
Run Code

Iterating and Seeding

With a database table in place, let's seed our models. Now is when things get interesting since we won't be manually seeding our campsites; instead, our ideal scenario is to be able to build and seed a model for each campsite the API has. There are two steps to that.

1. Obtain the data from the API 

To obtain the API, using the Rest Client class.
response = RestClient.get ‘https://developer.nps.gov/api/v1/campgrounds?stateCode=CO&api_key=MYAPIKEY'
You can also try this code with Online Ruby Compiler
Run Code

 

Let's now parse the JSON file that the API gave, which is now known as the result.

res = JSON.parse response
You can also try this code with Online Ruby Compiler
Run Code

 

2. Iterate over the JSON file of the API while building a new instance of the campsite in our rails application.

Obviously, the API you select will determine how this section works. The data we're seeking for using this API is nestled inside the main hash of the key called data. I'll simply build a new hash named sites that solely extracts the data from the data hash.

sites = result[“data”]
You can also try this code with Online Ruby Compiler
Run Code

 

Now we repeat! Let's iterate through the key-value pairs using the.each enumerable, and for each iteration, we'll construct a Campsite instance. The names of keys in the API we're obtaining from are "name" and "reservationURL," so I'm receiving those from there. It will resemble this in some ways.

sites.each do |site|
Campsite.create(
name: site[“name”],
url: site[“reservationUrl”]
)
end
You can also try this code with Online Ruby Compiler
Run Code

Versions

Tech firms frequently have multiple versions of their API, especially if they have been in business for a while. They typically started out with a first draught version and subsequently had to develop a real one, but they still have to maintain the original because so many other applications are probably going to be using it.

Always use the most recent version (there is typically a separate piece of documentation for each version). Pay attention to the documentation for the version you're viewing. Nothing compares to the frustration of realizing you were reading the v1 API documentation instead of the v2 API documents.

Kitten API

1. Your findings will appear at the bottom of the page after it has refreshed. After some meta data, you should see a long list of photo objects that your search produced. They resemble:

{ "id": "11357331313", "owner": "84345040@N00", "great": "6dd795c9c6", "server": "3805", "farm": 4, "title": "Gavin-Feb2013-0127", "ispublic": 1, "isfriend": 0, "isfamily": 0 },
You can also try this code with Online Ruby Compiler
Run Code

 

2. Below that, you can see the URL that they used to submit the request, which is more intriguing. To make the parameters more explicit, I've dissected them here:

http://api.flickr.com/services/rest/
?method=flickr.photos.search
&api_key=e0eb58bf4b3e29b253e86d6092e69dee
&tags=puppies
&format=json
&nojsoncallback=1
&api_sig=200efb63cb01a3d141fff12585e1e20a
You can also try this code with Online Ruby Compiler
Run Code

 

3. The URL includes the REST endpoint we previously examined, our search query, as well as some additional variables like the API key and format. The same batch of results will appear in your browser if you copy and paste it.
 

4. To really show a photo using Flickr's API, you must first gather the metadata for the image (which we just received in our search results), and then combine it into a URL that Flickr can use to actually retrieve the image. They advise the following format:

http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
You can also try this code with Online Ruby Compiler
Run Code

 

5. To display a photo, we can enter values from the previously received image:

http://farm4.staticflickr.com/3805/11357337313_6dd795c9c6.jpg
You can also try this code with Online Ruby Compiler
Run Code

 

Output

Output cat image


Flicker API

Just refers to the steps which we had done in the above kitten API, it will help you to create a ruby app. Then follow the steps

  • You'll need to provide some basic information about your app and sign in or create an account with Flickr (someone has to these days). Tell them how amazing your photo feed app will be by selecting "Apply for a non-commercial key." Along with a secret key, a key will be immediately generated for you. Copy both of these and store them someplace accessible later.
     
  • By clicking the "You" link in the top navbar when logged in, you can copy your Flickr ID from the browser address bar. It will have the following URL: https://www.flickr.com/photos/yourIDhere/. An illustration is 1895558555@N03. Later on, you'll require that for a few API methods.
     
  • Add a gem for the Flickr API to a fresh Rails application. For almost every API there is, there is a gem. Your API keys and secret keys must be included in all of them in some way. Select gems that are well-maintained (have recent commits) and widely used (GitHub stars is one way to get a good gauge for how valuable a gem is). As an alternative, you can look through RubyGems to find well-liked gems.
     
  • One thing to keep in mind is that having your secret key hard coded into your app is not a good idea because it makes the key hardly private, especially if you're pushing to GitHub. A better technique is to use a gem like figaro or to put the key in an environment variable (see docs). You may push your app's key right from the command line when it launches thanks to environment variables. Figaro works on the same premise, but it makes your life easier by letting you save the keys in a real file that isn't committed with the rest of your code. Unless you're a cowboy, use one of these methods.
     
  • Create a straightforward StaticPagesController to show a home page with a straightforward form. The form should just have a single text box that accepts a Flickr user's ID. The page should reload and show the user's photographs when the form has been submitted.

Restful external APIs in ruby on rails

Both your routes and your APIs should ideally be configured in a RESTful manner. The majority of APIs today are RESTful, thus the typical HTTP methods (GET, POST, PUT, PATCH, and DELETE) will fetch resources as expected. The benefit of structuring your application's routes RESTfully is that your API will function in a similar manner. 

Working with RESTful APIs at least eliminates a lot of the hassle because you can typically make an educated guess as to what you should be done before consulting the documentation to determine how precisely and in what format you'll receive the results. For example, just as you would anticipate a GET call to the /users route in your app to display a page listing all of its users, a GET request to a RESTful API for the same route should likely return a JSON or XML object filled with all the users (or at least some paginated sample of them).
 

OATH AND LOGIN VIA API

It resolves the serious issue of access control and user data privacy. The idea is that you should be able to submit requests on the user's behalf without requiring them to enter their password into your fantastic program. Oath thus enables Facebook to serve as a sort of middleman when interacting with the user.

The user can connect using an external website like Facebook and requests or submissions of data can be made on their behalf. 
 

OAUTH 2.0 BASICS

Every website will have conditions of use in addition to rate restricting their API. This normally specifies what you may do with the information you gather. For example, they probably won't permit you to store a significant amount of their data on your own database (harvesting). Additionally, they are probably not going to let you do anything spammy or detrimental to their users' experience. Your first rule of thumb should be common sense, but for specifics, go to the TOU documentation. In essence, you aren't allowed to do something if doing so will harm the user experience or take their sensitive data.
 

Restrictions

Every website will have conditions of use in addition to rate restricting their API. This normally specifies what you may do with the information you gather. For example, they probably won't permit you to store a significant amount of their data on your own database (harvesting). Additionally, they are probably not going to let you do anything spammy or detrimental to their users' experience. Your first rule of thumb should be common sense, but for specifics, go to the TOU documentation. In essence, you aren't allowed to do something if doing so will harm the user experience or take their sensitive data.
 

SDK

Many businesses offer SDKs in addition to or instead of API access (software development kits). These are often Javascript libraries with all the necessary code to access their API. This is advantageous since you can then use straightforward Javascript methods to access the API rather than performing elaborate backend tricks. However, it has the drawback of increasing your code base and requiring you to utilize their conventions everywhere.

Frequently Asked Questions

What do Rails serializers do?

A memory-based object is transformed into a stream of usable bytes through serialization. Ruby on Rails serializers transforms a given object into a JSON representation. The specific attributes that are rendered when an object or model is transformed into the JSON format are controlled by serializers.

Which is better, Ruby or Ruby on Rails?

While Ruby on Rails is an open source web development framework, Ruby is an open source, object-oriented general-purpose programming language. Ruby has its own "syntax" or grammar as a programming language, as well as certain guidelines for usage and application.

Describe the REST API service.

An application programming interface (API or web API) that complies with the requirements of the REST architectural style and permits interaction with RESTful web services is referred to as a REST API (also known as a RESTful API). Computer scientist Roy Fielding developed REST or representational state transfer.

Conclusion

In this article, we have discussed working with external APIs in ruby on rails ruby on rails, the introduction to ruby external apis in ruby on rails, steps to install the rest-client gem, its installation, creation of database, iteration, and seeding, versions, and restful APIs.

After reading about Introduction to Working with external apis in ruby on rails in ruby on rails, are you not feeling excited to read/explore more articles on the topic of file systems? Don't worry; Coding Ninjas has you covered. If you want to check out articles related to ruby, refer to these links, everything you wish to know about ruby on railsruby, and ruby on rails ,opportunity after mastering ruby on railsruby on rails for web development project.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to check your knowledge in coding, you may check out our mock test series and can participate in the contests hosted on Coding Ninjas Studio! But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundle for placement 

Happy Learning!

Live masterclass