Different ways of calling API in JavaScript

ZappyTalks
2 min readMar 18, 2022

JavaScript helps developers for both frontend and backend work and calling API in JavaScript is one of the main ways for interacting with backend or other services. JavaScript provides some built-in browser objects and some external open source libraries for calling APIs.

XMLHttpRequest object

It is the oldest way to make an API call and the XMLHttpRequest object is supported by all modern browsers. It’s the only option available to make an API call before ES6.

Here Is the typical syntax to make a request using the XMLHttpRequest object.

<script language="javascript" type="text/javascript">
function makeRequest(){
xhr = new XMLHttpRequest();
xhr.open("GET", "https://example.com/profile");
xhr.send();

xhr.onreadystatechange = function(){
document.getElementById("message-box").value = xhr.responseText;
};
}
</script>
<body>
<button onClick="makeRequest()">Make Request</button><br />
<textarea id="message-box" cols="40" rows="5"></textArea>
</body>

We can get any type of data using XMLHttpRequest, whether it’s json, xml, html etc.

Fetch API

The Fetch API provides a JavaScript interface to fetch resources across the networks. It provides a global fetch() method that provides an easy, logical way for making a request.

The fetch() method takes one mandatory argument, the path to the resource that wants to fetch.

It returns a Promise that resolves to the Response to that request — as soon as the server responds with headers — even if the server response is an HTTP error status.

Promises are captured by the `then()` method and Rejected promises can be captured by the `catch()` method.

Let’s take a look on syntax:

fetch('https://example.com/profile)
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});

Axios

Axios is a promise-based HTTP Client for node.js and the browser. It uses the native node.js http module on the server-side, while on the client (browser) it uses XMLHttpRequests. Axios needs to install in your project to use for making API requests.

Let’s take a look on syntax:

const axios = require('axios');const axios = require('axios').default;// Make a request for a user with a given ID
axios.get('https://example.com/profile')
.then(function (response) {
// handle success
console.log(response);
}).catch(function (error) {
// handle error
console.log(error);
}) .then(function () {
// always executed
});

jQuery AJAX

AJAX stands for Asynchronous JavaScript and XML. It is used to handle asynchronous HTTP requests.

$.ajax() method is used to perform asynchronous requests. It takes several parameters but url is a mandatory parameter. Also, it has callback functions to handle response.

Look at the syntax:

var jqxhr = $.ajax({
url: "https://example.com/profile",
beforeSend: function() {
}
}).done(function() {
alert( "success" );
}) .fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});

Originally published at https://zappytalks.com on March 18, 2022.

--

--

ZappyTalks
0 Followers

Let’s simplify and feel either informed or inspired