How to call an API using JavaScript?

Sun Apr 02 2023

8 min read

APIs have emerged as a vital tool for meaningfully accessing and utilizing this data. APIs allow developers to connect their applications to external services, databases, or platforms and can be a powerful tool for building dynamic, data-driven web applications.

JavaScript offers several ways to interact with APIs. However, getting started with APIs can be daunting since there are multiple ways to call an API, and figuring out how to parse the data can take time and effort.

This guide will walk you through calling an API using JavaScript. Next, we'll choose a public API to work with and go through the steps of making the API call and handling the response.

Four ways to make an API call in JavaScript

There are several ways to make an API call in JavaScript. Let's take a look at the most popular ones.

XMLHttpRequest

This is a legacy way of making API requests in JavaScript that are still supported by modern browsers. It's more verbose than fetch() and uses callbacks instead of Promises.

Loading component...

Fetch API

This is a built-in function in modern browsers that make it easy to make network requests and handle responses using Promises.

Loading component...

Axios

Axios is a popular third-party library for making API requests in JavaScript. It's similar to fetch() in terms of its API but offers additional features like request cancellation and automatic JSON parsing.

Loading component...

jQuery

jQuery.ajax() is a method the jQuery library provides for making API requests. It's similar to XMLHttpRequest in terms of its API but offers additional features like automatic JSON parsing and support for cross-domain requests.

Comparison of the four ways of making API calls using JavaScript

Here's a table summarizing the differences between the four methods of making API calls in JavaScript:

MethodAdvantagesDisadvantages
XMLHttpRequestLegacy API that is widely supportedMore verbose and uses callbacks instead of Promises
fetch()Modern API for making requestsRequires handling of Promises or async/await
axiosPopular third-party library with additional featuresAdds additional overhead to project
jQuery.ajax()jQuery method that is similar to XMLHttpRequest with additional featuresRequires including jQuery library in project

Now, let's take a look at how these four ways can be compared to each other in terms of code. We will use the https://jsonplaceholder.typicode.com/users URL to get a list of user data in JSON format. The data returned by the above endpoints will be similar to the following:

json
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
....
]

Making the API Call with XMLHttpRequest

XMLHttpRequest is a legacy way of making API requests in JavaScript that are still supported by modern browsers. It's more verbose than fetch() and uses callbacks instead of Promises. Here's an example of how you could use XMLHttpRequest to make a request to the API endpoint:

js
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users');
xhr.onload = function() {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
} else {
console.error(`Error: ${xhr.status}`);
}
};
xhr.onerror = function() {
console.error('Request error');
};
xhr.send();

In this example, we create a new instance of XMLHttpRequest and call its open() method with the HTTP method and API endpoint URL as arguments. We then define an onload() function to handle the response asynchronously. If the status code is 200 (i.e., the request was successful), we parse the response text as JSON and log it to the console. If the status code is anything other than 200, we log an error message to the console. Finally, we define an onerror() function to handle any errors that may occur during the request.

Making the API Call with Fetch

The fetch() method is a newer and more modern way of making API calls in JavaScript. It provides a simpler and more streamlined API compared to the traditional XMLHttpRequest way, and it also supports promises and the async/await syntax.

fetch() is built into modern browsers, so you don't need to include any additional libraries to use it. Here's an example of how you could use fetch() to make a request to the API endpoint:

js
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

In this example, we call fetch() with the API endpoint URL as its argument. We then use the then() method to handle the response asynchronously. The first then() method calls the json() method on the response object to parse the response as JSON. The second then() method logs the parsed JSON data to the console. The catch() method is used to handle any errors that may occur during the request.

Using the async/await syntax, the above fetch() method will be like the following:

js
async function getUsers() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
getUsers();

In this example, we define an async function called getUsers(). Within the function, we use the await keyword to wait for the fetch() request to complete and return a response object. We then use the json() method on the response object to extract the JSON data, which we assign to the data variable using another await keyword. Finally, we log the data variable to the console.

Note that we wrap the entire function in a try/catch block to handle any errors that may occur during the request. We also call the getUsers() function at the end to execute the request.

Making the API Call with Axios

axios is a popular third-party library for making API requests in JavaScript. It's similar to fetch() in terms of its API but offers some additional features like request cancellation and automatic JSON parsing. Here's an example of how you could use axios to make a request to the API endpoint:

js
import axios from "axios";
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((response) => console.log(response.data))
.catch((error) => console.error(error));

In this example, we call axios.get() with the API endpoint URL as its argument. We then use the then() method to handle the response asynchronously. The then() method logs the data property of the response object to the console. The catch() method is used to handle any errors that may occur during the request.

Note that in order to use axios, you need to include the Axios library in your project as shown in the code snippet above.

Making the API Call with jQuery

jQuery.ajax() is a method provided by the jQuery library for making API requests. It's similar to XMLHttpRequest in terms of its API but offers some additional features like automatic JSON parsing and support for cross-domain requests.

Here's an example of how you could use jQuery.ajax() to make a request to the API endpoint:

js
import $ from "jquery";
$.ajax({
url: 'https://jsonplaceholder.typicode.com/users',
method: 'GET',
success: function(data) {
console.log(data);
},
error: function(error) {
console.error(error);
}
});

In this example, we call $.ajax() with an object containing the API endpoint URL and the HTTP method as its arguments. We then define a success function to handle the response asynchronously. The success function logs the data parameter to the console. We also define an error function to handle any errors that may occur during the request.

Note that in order to use jQuery.ajax(), you need to include the jQuery library in your project as shown in the code snippet above.

Loading component...

Performance

When it comes to performance, fetch() is generally considered to be the most performant method for making API requests in modern browsers. This is because fetch() is a modern API that is built into the browser and is designed to take advantage of newer browser features like Promises and the async/await syntax.

However, it's worth noting that performance can depend on a variety of factors, such as the size of the data being transferred, the speed of the network connection, and the specific use case of the API request. Additionally, some third-party libraries like axios may offer additional performance benefits in certain situations, such as when making requests that require specific features like request cancellation or response caching.

Overall, it's important to consider the specific needs of your project and to benchmark different methods of making API requests to determine which one provides the best performance for your use case.

Conclusion

In this guide, we've explored the process of calling an API using JavaScript. Calling APIs with JavaScript can be a powerful way to incorporate third-party data and functionality into your web applications. By following these tips and best practices, you can make the most of this powerful tool and build robust, dynamic applications.