Consume Five APIs From RapidAPI Hub in Five Languages

Wed Jun 29 2022

19 min read

When you have to start a new project, you first work on the functional requirements. You pen down everything your application should have to achieve its goal. You also choose the best technology to build your front-end and the server. If it’s a Jamstack application, you only concern yourself with the client-side technology.

It’s important that you create these requirements beforehand. Once the project transitions to the development stages, all this becomes difficult to change.

You must also consider the server APIs if you are working on a full-stack project. Without APIs, your server is of no use to the client-side. It will not be able to communicate with the client. The same is true for the front-end. Without APIs, it is just static markup with no dynamic data.

So in a client-server architecture, server APIs play a crucial role. Without them, there is no communication. Earlier, I mentioned that Jamstack apps do not need a server. The reason is simple. They make use of public APIs available on the internet.

So far, we have established that your project will not work without APIs. APIs are crucial everywhere, whether it is client-server architecture or Jamstack. But what is this API? Where can we find them? And how can we call them?

These are some questions that we will answer in this piece. So without wasting any time, let’s jump right in!

What Is an API?

Let’s start with the first question. To understand the concept, we will look at a simple example. Imagine living in old times when there were no telephones and internet. You want to send a letter to your friend who lives at the other end of the town. What would you do? You will write the letter and send it via post. The postman will take your letter and deliver it to him. Here, the postman is the API.

Let’s have a deeper look. You and your friend are two separate entities, and you want to talk with each other. In this case, you are the client, and your friend is the server. To communicate, you rely on a postman (the API) to take your messages to each other.

The Application Programming Interface (API) is like a middle man who connects two sides; a waiter takes your order and brings you food. It is a channel that applications utilize to talk with each other. You put some information at one end, and the API takes that information and returns back with a result.

Your application
Jokes application

The API also lets you utilize the capabilities of another application. For instance, if you are developing a weather app and wish to know the user's location, you can use any geolocation API to get the user's location. Such APIs are public APIs.

Where can we find APIs?

The answer to this question is not simple. APIs have multiple types. Let’s look at each API type and learn where we can find them.

Web APIs

When you are building a website, there are many Web APIs available that you can use. These APIs are provided to the developers by the browser. They are easy to use and offer a wide range of built-in features. For example, the Fetch API lets you get data from a server, and the DOM API allows you to manipulate the DOM elements. Both of these are web APIs.

We have written several guides on web APIs. You can find all of them here.

Internal APIs

These server APIs help your client and server communicate with each other. They have different architectures, such as RESTful APIs, GraphQL APIs, RPC, SOAP APIs, etc.

The internal APIs are private. They are used within an organization to build their products. These are also the APIs that service-based companies make for their client's products. If you want to build your own RESTful API, I suggest reading this piece.

Public APIs

Public APIs are accessible to all the developers and other users. They are also called external APIs because external or third-party developers can access them.

They allow users to authenticate and authorize themselves with minimal restrictions. The registration may be in the form of an API Key or OAuth or be completely open. They are usually targeting external users to share different data or services.

You will have to surf the internet to find a good public API. Even if you have found one, it is unknown whether it will be up all the time. It might not have proper documentation. Countless things can go wrong with the API.

That is where RapidAPI Hub comes in and saves the day. All you need is an account, and you will have thousands of good public APIs at your call. You can even publish your APIs on it to earn some side money.

Get access to thousands of APIs
RapidAPI saves you the time and effort of searching for an API on the internet. It is a huge API hub that provides access to different API categories.
Read more

How can we call APIs?

There is still an unanswered question about how to use these APIs. In this piece, I will not go into detail about how to consume internal or web APIs but instead focus on public APIs. We will use five different APIs from RapidAPI Hub and call them in five different programming languages. It will be a step-by-step process to make things easier and simple to follow.

Before starting, please ensure that you have signed up on the RapidAPI Hub. Go ahead and do it. I will wait.

1. JavaScript

Let’s start with JavaScript. It is a programming language that could only run inside the browser before Node.js. It has several frameworks and libraries that are used across the world for different tasks. You can write your entire website inside JavaScript. You can build mobile applications, code games, work on machine learning, render graphics, etc., all while utilizing the power of a single language.

Let’s look at how to call APIs in JavaScript using the fetch web API that the browser provides.

→ STEP #1

Let’s find an API that we can use. Head to RapidAPI Hub and sign up if you haven’t already.

When you are signed in, search for jokes APIs. To show how to make API calls in JavaScript, I will use Jokes API by API-Ninjas. It is a free API, so you do not need to subscribe. However, you will need your RapidAPI key. So go ahead and save the value of x-rapidapi-key somewhere to use later.

→ STEP #2

Create a directory on your computer and open it in your preferred code editor. Once you are done, create an HTML file called index.html inside this directory. Now write a basic HTML boilerplate. I have also provided it below that you can copy and paste.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Consume APIs in JavaScript</title>
</head>
<body>
<script></script>
</body>
</html>

→ STEP #3

RapidAPI Hub provides you with code snippets in different languages for integrating the API. Since we are learning to use APIs in JavaScript from RapidAPI Hub, let’s go (JavaScript) fetch code snippet since fetch is a web API used for calling REST APIs.

Now paste the code snippet inside the script tag.

html
<script>
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Host': 'jokes-by-api-ninjas.p.rapidapi.com',
'X-RapidAPI-Key': 'your-rapidapi-key'
}
};
fetch('https://jokes-by-api-ninjas.p.rapidapi.com/v1/jokes', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
</script>

Go ahead and replace the value of your-rapidapi-key with the API key you saved earlier. Once you are done, run this file and open your console. You will see that the fetch API has called the Jokes API and after receiving the response, logged it in the console.

Here is a demo of how you can call APIs from RapidAPI Hub in JavaScript:

Vanilla JavaScript

Make sure you enter your RapidAPI key before clicking the Call API button. You can also replace the API with any API from RapidAPI (if the API does not take any query parameter).

2. Python

The next we will look at is Python. It is one of the most widely used programming languages with thousands of applications. It is not just limited to Machine Learning but also has several frameworks for web development. You can use Django to develop a full-stack web app or Flask to develop your application’s backend with Python.

Let’s take a look at how we can call APIs in Python.

→ STEP #1

Just like before, we will use RapidAPI Hub to find the API we will use.

Once you have signed up, you will see thousands of APIs at your beck and call. I have already found a freemium Random Facts API that we will use.

Subscribe to Random Facts API

To use this API, you need to subscribe to it first. Go ahead and click on the subscribe button below. It will take you to the API page where you can choose the free package.

Subscribe

When you are done, you will be redirected back to the original page. Here, you will find see your RapidAPI key. It will be used later so please go ahead and save the value of x-rapidapi-key somewhere.

→ STEP #2

Make sure you have Python installed on your computer. Now create a directory and open it in your preferred code editors. I am using VSCode.

You should create a virtual environment when working with Python, so your packages are not installed globally. The virtual environment can be created using Python’s virtualenv package.

You can install this by opening your terminal and running the following command there:

sh
pip install virtualenv

This command will globally install virtualenv package on your computer. Now open your terminal again and run the following command:

sh
virtualenv env

It will create an env directory with your virtual environment files. There is no need to change and open any files in the virtual environment.

There are different commands to activate the virtual environment on Linux and Windows. Choose the command from below that fits the bill for you:

sh
# for linux
source env/Scripts/activate
# for windows
source env/bin/activate

Ensure you activate the virtual environment by running the command according to your operating system.

→ STEP #3

Once your virtual environment is activated, install Python’s requests package by running the following command in the terminal:

sh
pip install requests

It will install the requests package locally in your project.

→ STEP #4

Now create a file called app.py in the root directory of your project. Open this file and import the requests package at the top:

py
import requests

On the Random Facts API page, you will find code snippets of how you can use this API with different languages. Since we are using Python, let’s choose the (Python) Requests from the dropdown.

Copy the code snippet and paste it into your app.py file.

py
import requests
url = "https://random-facts2.p.rapidapi.com/getfact"
headers = {
'x-rapidapi-host': "random-facts2.p.rapidapi.com",
'x-rapidapi-key': "your-rapidapi-key"
}
response = requests.request("GET", url, headers=headers)
print(response.text)

Go ahead and replace the value of your-rapidapi-key with the API key you saved earlier. Once you are done, run the code by opening the terminal and running the following:

sh
python app.py

You will see a random fact from the API printed on the terminal. Once you are done, you can deactivate the virtual environment by running the following command:

sh
deactivate

3. Go

The Go programming language is an open-source project supported by Google. Focused on fast execution and ease of learning, Go has gained popularity, especially in areas like cloud engineering.

APIs are the backbone of any application, so let's see how we can call APIs in a Go application.

→ STEP #1

Let’s find another API from RapidAPI Hub which we will call using Go. I have already found an API that we will consume. It’s called CarbonFootprint API that gives us the carbon footprint data of travel.

Subscribe to CarbonFootprint API

To use this API, you need to subscribe to it first. Go ahead and click on the subscribe button below. It will take you to the API page, where you can choose the free package.

Subscribe

As we did before, we need to save the value of x-rapidapi-key because it will be used later as an authentication token.

→ STEP #2

Now, let's get our hands dirty and start writing the code to consume the API. Go ahead and create a Go file named main.go. The first thing we will do in this file is import the required packages. We will add the following:

go
package main
import(
"net/http"
"fmt"
"io/ioutil"
)

The net/http package deals with HTTP servers/clients and provides functionalities required to make HTTP requests. fmt and io/ioutil implement some necessary I/O functions.

→ STEP #3

We will use the NewRequest function of the http package to specify our API call because it allows us to set custom headers. The function takes three parameters.

  1. HTTP Method.
  2. API Endpoint URL.
  3. Request Body (optional).

Let's add this function.

go
package main
import(
"net/http"
"fmt"
"io/ioutil"
)
func main() {
url := "https://carbonfootprint1.p.rapidapi.com/CarbonFootprintFromCarTravel?distance=100&vehicle=SmallDieselCar"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Print(err.Error())
}
}

We also added an if statement to catch any possible errors and log them. We will use the Header.Add function to add headers in our API request. Let's add our API key using it.

go
package main
import(
"net/http"
"fmt"
"io/ioutil"
)
func main() {
url := "https://carbonfootprint1.p.rapidapi.com/CarbonFootprintFromCarTravel?distance=100&vehicle=SmallDieselCar"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Print(err.Error())
}
req.Header.Add("x-rapidapi-key", "YOU_API_KEY")
}

Now we can send the request to receive the response from the API.

go
package main
import(
"net/http"
"fmt"
"io/ioutil"
)
func main() {
url := "https://carbonfootprint1.p.rapidapi.com/CarbonFootprintFromCarTravel?distance=100&vehicle=SmallDieselCar"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Print(err.Error())
}
req.Header.Add("x-rapidapi-key", "your-rapidapi-key")
res, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Print(err.Error())
}
}

Go ahead and replace the value of your-rapidapi-key with the API key you saved earlier.

→ STEP #4

Finally, we can display the data returned by the API. Firstly, the client must close the response body when finished with it:

go
defer res.Body.Close()

Now, we can access the response body using the ioutil.ReadAll function. After checking for errors, we can display the response as a string.

go
package main
import(
"net/http"
"fmt"
"io/ioutil"
)
func main() {
url := "https://carbonfootprint1.p.rapidapi.com/CarbonFootprintFromCarTravel?distance=100&vehicle=SmallDieselCar"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Print(err.Error())
}
req.Header.Add("x-rapidapi-key", "your-rapidapi-key")
res, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Print(err.Error())
}
defer res.Body.Close()
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
fmt.Print(err.Error())
}
fmt.Println(string(body))
}

Run the file through your terminal, and you will see the API response like this:

json
{
"carbonEquivalent": 17.137
}

4. Ruby

Ruby was first released in 1993, but it gained popularity after Ruby on Rails, an MVC framework, was developed in 2005. It is a scripting language famous for its simple and easy-to-understand syntax. It takes code-readability to the extreme while being an object-oriented language.

Ruby is a dynamically typed language where everything is an object. It is being used by companies like Twitter, GitHub, Shopify, etc. Let’s take a look at how we can call APIs in Ruby.

→ STEP #1

Like we did earlier, we will again use RapidAPI Hub to find a new API to call in Ruby. And just like before, I have already found an API for us. It’s called [Bing News Search API(https://RapidAPI.com/microsoft-azure-org-microsoft-cognitive-services/api/bing-news-search1/?utm_source=RapidAPI.com%2Fguides&utm_medium=DevRel&utm_campaign=DevRel) that provides global news information.

Subscribe to Bing News Search API

To use this API, you need to subscribe to it first. Go ahead and click on the subscribe button below. It will take you to the API page where you can choose the free package.

Subscribe

Please make sure you have saved the value of x-rapidapi-key because it will be used later.

→ STEP #2

You need to download and install Ruby on your computer. For this, go to this site and download the stable version. Once it is done downloading, go ahead and install it.

Now open your terminal and run the following command to check if Ruby has been successfully installed or not:

sh
ruby -v

→ STEP #3

Create a directory on your computer and open it in your preferred code editor. Once you are done, create a Ruby file called app.rb inside this directory. Open this file and import the following packages at the top like this:

rb
require 'uri'
require 'net/http'
require 'openssl'

These packages will be used to make API calls and deal with SSL.

Now we need to add the API endpoint, which we will call:

rb
url = URI("https://bing-news-search1.p.rapidapi.com/news?safeSearch=Off&textFormat=Raw")

Once done, we will set the SSL certificate. For this article, I am setting the verification to none.

rb
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

Now let's call the API using the net/http package we imported earlier.

rb
request = Net::HTTP::Get.new(url)
request["x-rapidapi-host"] = 'bing-news-search1.p.rapidapi.com'
request["x-rapidapi-key"] = 'your-rapidapi-key'
response = http.request(request)

Here, we are making a GET request to the API using the API key provided by the RapidAPI Hub. Replace the value of the x-rapidapi-key in the above code snippet with the API key you saved earlier.

We also need to handle the response. For the sake of this article, let's print it out on the terminal:

rb
puts response.read_body

In the end, the code in app.rb will look like this:

rb
require 'uri'
require 'net/http'
require 'openssl'
url = URI("https://bing-news-search1.p.rapidapi.com/news?safeSearch=Off&textFormat=Raw")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(url)
request["x-rapidapi-host"] = 'bing-news-search1.p.rapidapi.com'
request["x-rapidapi-key"] = 'your-rapidapi-key'
response = http.request(request)
puts response.read_body

Now run the file using the following command:

sh
ruby app.rb

You will get an object from the API with a value key inside it which will be an array holding all the news information.

5. Java

It is a multi-purpose object-oriented language that runs on over 3 billion devices. You can build all types of things in Java, from web apps to mobile and desktop applications. You can even write games in Java. It is an open-source language that is free, fast, and powerful. The language is intended to build cross-platform applications where developers have to write code only once, and the app works on all operating systems.

Let’s take a look at how we can call APIs in Java.

→ STEP #1

Now for Java, I will use the Famous Quotes API from RapidAPI Hub.

Subscribe to Famous Quotes API

To use this API, you need to subscribe to it first. Go ahead and click on the subscribe button below. It will take you to the API page, where you can choose the free package.

Subscribe

Please ensure you have saved the value of x-rapidapi-key because it will be used later.

→ STEP #2

Java needs a compiler to compile its code. Without it, your code will not run. So before we do anything, click on this link and download the Java SDK for your operating system. Once it is downloaded, go ahead and install it.

To check everything has taken place as expected, open your terminal and run the following command:

sh
javac –version

You should see a version number when you run the command. If you don’t, please restart your system.

→ STEP #3

The Java files have an extension of .java. So, go ahead and open your preferred code editor and create a call.java file inside it. It will give you an empty Java file.

→ STEP #4

We will use the HttpRequest package from the Java SDK to create an API call. So let’s import it at the top of the file.

java
import java.net.http.HttpRequest;

To handle the response we will receive from the HttpRequest package, we have to use the HttpResponse package.

java
import java.net.http.HttpResponse;

Now to send the API call, we would need to import another package. So let’s do it.

java
import java.net.http.HttpClient;

Let’s import the Java IOException package to handle exceptions in our code.

java
import java.io.IOException;

→ STEP #5

Now create a class, and inside it, write the main function. You can copy the code snippet below to do it.

java
class call {
public static void main(String[] args) {
}
}

Now let’s create an HttpRequest builder to add all the things we need to call an API.

java
class call {
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://famous-quotes4.p.rapidapi.com/random?category=all&count=2"))
.header("X-RapidAPI-Host", "famous-quotes4.p.rapidapi.com")
.header("X-RapidAPI-Key", "your-rapidapi-key")
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
}
}

You can see that we have created a builder, giving it the API endpoint by passing it as a parameter to the uri method. Afterward, we set the header values to provide details like API host and API key. You should replace the value of X-RapidAPI-Key with the value you saved earlier in step #1.

Now we need to create a simple HttpResponse variable to save to the response we will receive from the API.

java
class call {
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://famous-quotes4.p.rapidapi.com/random?category=all&count=2"))
.header("X-RapidAPI-Host", "famous-quotes4.p.rapidapi.com")
.header("X-RapidAPI-Key", "your-rapidapi-key")
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> response = null;
}
}

Finally, we need to send the API call. The HttpClient package will be used here.

java
class call {
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://famous-quotes4.p.rapidapi.com/random?category=all&count=2"))
.header("X-RapidAPI-Host", "famous-quotes4.p.rapidapi.com")
.header("X-RapidAPI-Key", "your-rapidapi-key")
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> response = null;
try {
response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(response.body());
}
}

Error handling while making API requests is essential. That’s why I have enwrapped the API request within a try/catch block because the call can fail, leading to an error. Now go ahead and run this file in the terminal. It will make an API call and print the response in the terminal.

Wrap Up

That’s all, folks! Now you know about what an API is, where you can find it, and how you can call it in five different languages. So, go ahead now and try it yourself.