How to get data from an API in JavaScript?

•

Mon Sep 26 2022

•

11 min read

JavaScript is one of the most widely used languages due to its unlimited use cases for the web, mobile, machine learning, game development, etc. Since the language was initially used only on the web to make websites dynamic and interactive, JavaScript is full of valuable features. One of them is built-in web APIs.

JavaScript provides multiple ways to get data from an API. You can either use built-in web APIs to get the data or install third-party HTTP libraries.

The following are the ways we will cover in this piece to get data from an API in JavaScript.

  1. Fetch built-in web API
  2. XMLHttpRequest web API
  3. Axios (third-party package)
  4. Got (third-party package)
  5. node-fetch (third-party package)

In this piece, let’s look at some (if not all) ways to get data from an API in JavaScript. So without any further ado, let’s jump in!

1. Using Fetch API to get data from API

The Fetch API is a web API provided by the browser, so developers can call other public API using it. The browser exposes it by giving out a fetch method that takes multiple parameters. The first is the API you want to call, whereas the second optional parameter is an object that holds all the information you need to make the request successful.

Let’s break it down in steps to make things simpler.

→ STEP #1

The first thing we have on the list is finding an API we can call. For this, let’s head to RapidAPI Hub.

Loading component...

I have already found an API for us to use that lets you search anything on the web. It’s called Web Search API. Please go ahead and subscribe to the API.

→ STEP #2

Now create an empty directory inside your computer and open it in your preferred code editor. Once opened, create an index.html file inside this directory and paste the following code there.

html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Using Fetch API to get data from API</title>
</head>
<body>
</body>
</html>

→ STEP #3

We can use fetch API in two ways: promise-chaining or async-await. Let’s try out the promise-chaining approach.

html
<script>
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'your-rapidapi-key',
'X-RapidAPI-Host': 'contextualwebsearch-websearch-v1.p.rapidapi.com',
},
};
fetch(
'https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/ImageSearchAPI?q=taylor%20swift&pageNumber=1&pageSize=5&autoCorrect=true',
options
)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
</script>

If you look at the above code closely, you will find we provided two parameters to the fetch method, as mentioned earlier. The first is the API key, whereas the second is the options object that holds the HTTP method and request header.

Using promise-chaining, we received a response to our API call, which we handled inside the then method. We also performed error handling using catch in case there is an error.

Go ahead and replace 'your-rapidapi-key with the API key you received when you signed up on RapidAPI Hub. It’s also available on the API playground of Web Search API.

Using fetch API is really simple. Just provide it with an API and HTTP method along with the essentials. If you want to learn more about fetch API, I recommend you look at this interactive guide we have curated around it.

2. Using XMLHttpRequest to get data from API

XMLHttpRequest API is another web API that lets you get data from an API using JavaScript without refreshing the web page. Despite its name, the XMLHttpRequest API is not limited to XML data. You can also request JSON data via this API.

Please follow the steps below to learn more about how to get data from an API using XMLHttpRequest.

→ STEP #1

Just like before, we need to find an API first, which we will call using XMLHttpRequest. For this, let’s head to RapidAPI Hub.

Loading component...

I have already found an API we can use to learn more about using XMLHttpRequest API. It’s called E-mail Check Invalid or Disposable Domain API, and it lets you validate an email address. Please go ahead and subscribe to it.

→ STEP #2

You need to create a project. For this, create a folder on your computer and open it in your preferred code editor. Once you are done, create a file called index.html in your project directory and add basic HTML boilerplate code inside it.

html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Using XMLHttpRequest API to get data from API</title>
</head>
<body>
</body>
</html>

→ STEP #3

Now let’s see how you can make the request. First, you need to initialize the XMLHttpRequest API instance. Here is how you do it:

js
const xhr = new XMLHttpRequest();

Now we need to call the open method.

js
xhr.open(method, url);

We need to change the response type to JSON to let the API know that we need JSON formatted data:

js
xhr.responseType = 'json';

The last thing we need to do is send the request. Here is how you do it:

js
xhr.send();

You also need to handle the response you receive when you make the API call. For this, you set onload event listener on the XMLHttpRequest instance.

js
xhr.onload = () => {
console.log(xhr.response);
};

You can also wrap the entire XMLHttpRequest code in a promise and then await it to make it asynchronous. Go ahead and copy the following code in your HTML file.

html
<script>
const sendRequest = (method, url, header) => {
const promise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
header.map(obj => xhr.setRequestHeader(obj.name, obj.value));
xhr.responseType = 'json';
xhr.onload = () => {
if (xhr.status >= 400) {
reject(xhr.response);
}
resolve(xhr.response);
};
xhr.send();
});
return promise;
};
const getData = async () => {
try {
const res = await sendRequest(
'GET',
'https://mailcheck.p.rapidapi.com/?domain=mailinator.com',
[
{
name: 'X-RapidAPI-Key',
value: 'your-rapidapi-key',
},
{
name: 'X-RapidAPI-Host',
value: 'mailcheck.p.rapidapi.com',
},
]
);
console.log(res);
} catch (err) {
console.log(err);
}
};
getData();
</script>

Please replace your-rapidapi-key with your RapidAPI key. I have also set the headers using xhr.setRequestHeader function that takes two parameters. The first is the header key, and the second is the header value.

Go ahead and try it out yourself.

3. Using Axios to get data from API

Axios is an open-source, promise-based HTTP client. It uses JavaScript’s promises to send HTTP requests and manage their responses. Moreover, it offers additional features for fetching APIs that are not available in the basic Fetch API. Some of these features include:

  • Request interceptors
  • Custom instances
  • Request timeouts and cancellations

Let’s look at how we can get data using Axios.

→ STEP #1

We will again use an API from RapidAPI Hub. This time, we will use the Famous Quotes API. Please go ahead and subscribe to it.

→ STEP #2

Create an empty directory inside your computer and open it in your preferred code editor. Now create an index.js inside this directory. Lastly, open your project terminal and run the following command to install axios.

sh
npm install axios

→ STEP #3

Take a look at the snippet below. If you want to make a GET request, you will use the get method of axios. If you have to make a POST, PUT, or DELETE request, you will use post, put, or delete method of axios. These are called HTTP methods.

The first parameter of these HTTP methods is the API you want to request, whereas the second parameter is an object where you can send params, headers, and your API request. The header is generally the area where you will add your API key.

js
import axios from 'axios';
const fetchQuotes = async () => {
try {
const res = await axios.get(
`https://famous-quotes4.p.rapidapi.com/random`,
{
headers: {
'x-rapidapi-host': 'famous-quotes4.p.rapidapi.com',
'x-rapidapi-key': 'your-rapidapi-key'
},
params: {category: 'all', count: '10'}
}
);
} catch (err) {
console.log(err);
}
};
fetchQuotes()

You can see that I have imported axios at the top of the file and used it with async/await to get data from an API.

4. Using Got to get data from API

Got is another third-party package we can use to get data from an API. It is a lightweight, human-friendly, powerful HTTP request library that is explicitly designed to work with Node.js. It supports pagination, RFC-compliant caching, makes an API request again if it fails, supports cookies out of the box, etc.

→ STEP #1

Let’s find an API first that we can call using got. For this, let’s head to RapidAPI and sign up quickly. Once you are done, you will have access to thousands of APIs. All you need is to subscribe to them, and you are good to go.

The API we will use to learn how to use got to get data is Car Data API. It returns information about cars related to their make, model, etc. Please go ahead and subscribe to the API.

→ STEP #2

Like before, create a project directory and open it in your preferred code editor. Once you do this, create a JavaScript file inside it called index.js. This file will contain all the code we need to get data from an API.

Now, run the following command in your terminal to install got in your project.

sh
npm install got

→ STEP #3

Just like axios, we need to import got at the top.

js
import got from 'got';

got uses an HTTP method to call API. You can use a method using got.HTTP_METHOD. In the case of a GET request, it will be got.get, whereas with the POST request, the syntax will be got.post.

js
import got from 'got';
got.get('https://car-data.p.rapidapi.com/cars/types', {
headers: {
'X-RapidAPI-Key': 'your-rapidapi-key,
'X-RapidAPI-Host': 'car-data.p.rapidapi.com',
},
})
.json()
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});

As you can see that I have used the promise-chaining to handle the API response and error. I have made a GET request to the Car Data API using got. I provide an object as a second parameter that holds another object for headers. Afterward, I converted the response to JSON and then logged it on the console.

One thing you would want to know is that you can use got only with Node.js, whereas axios can be used on the client side as well.

Go ahead and try it out yourself.

5. Using node-fetch to get data from API

node-fetch is a lightweight npm package that lets you use fetch API in Node.js. The node-fetch package has over 36 Million weekly downloads, and currently, more than 5.5 Million projects rely on it. It has almost 7.9k stargazers and 952 forks. The package is well-maintained, so you would not have to worry about bug fixes.

Let’s go ahead and try node-fetch to get data from an API.

→ STEP #1

We can use RapidAPI Hub again to find an that we can use with node-fetch.

Loading component...

To learn how to use node-fetch, we will use the Jokes API. Please go ahead and subscribe to it.

→ STEP #2

Create an empty directory and open it in your preferred code editor. Once you are done, create a JavaScript file called index.js. Finally, install node-fetch in your project by running the following command on the terminal:

sh
npm install node-fetch

→ STEP #3

Let’s import node-fetch at the top of index.js file.

js
import fetch from 'node-fetch';

node-fetch is very similar to fetch API. If you know how to use fetch API to call APIs in JavaScript, you can easily pick up node-fetch.

js
import fetch from 'node-fetch';
const url = 'https://jokes-by-api-ninjas.p.rapidapi.com/v1/jokes';
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'your-rapidapi-key',
'X-RapidAPI-Host': 'jokes-by-api-ninjas.p.rapidapi.com',
},
};
fetch(url, options)
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.error('error:' + err));

You can see in the above code snippet that I have an API endpoint and an options object which I have passed to the fetch API of node-fetch. I have used promise-chaining to handle the response which I log on to the console.

Go ahead and try it out yourself.

Wrap Up

That’s all, folks! We have covered five different ways to get data from API in JavaScript. Throughout this piece, we constantly used RapidAPI to find different APIs to call. If you want to learn more about RapidAPI Hub, I recommend you look at this piece.