Here are 5 different ways to make API calls in JavaScript.

Roman
4 min readSep 16, 2024
Photo by Noam Cohen on Unsplash

Javascript is a client-side scripting language, normally we cannot access the database to fetch & manipulate records. To request data from the server javascript provides some methods that we use to fetch data asynchronously from the server without reloading the whole webpage.

In this article, we’ll see 5 different ways to make API calls in JavaScript. You can also see 5 different ways to make API call in reactjs.

1) XMLHttpRequest()

The XMLHttpRequest() method is the first javascript method introduced to make API calls asynchronously. It is the standard way of making API calls in JavaScript, but it is a bit more complicated to use.

Let’s understand with an example:

function getCountries() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://restcountries.com/v3.1/all");
xhr.onload = function() {
if(xhr.status == 200) {
const data = JSON.parse(xhr.responseText);
console.log("Response data: ", data);
} else {
console.log("Request failed with status: ", xhr.status);
}
};

xhr.onerror = function() {
console.error("Network Error");
}

xhr.send();
}

getCountries();

In this example, I have made a GET request. You may have noticed that in the old days making…

--

--