4 Ways to Make an API Call in JavaScript
Last Updated :
28 Aug, 2024
API(Application Programming Interface) is a set of protocols, rules, and tools that allow different software applications to access allowed functionalities, and data, and interact with each other. API is a service created for user applications that request data or some functionality from servers.

To give specific access to our system to other applications that may be useful to them, developers create APIs and give them endpoints to interact and access the server data. While working with JavaScript it is common to interact with APIs to fetch data or send requests to the server.
4 Ways to Make an API Call in JavaScript:
1. API Call in JavaScript Using XMLHttpRequest
XMLHttpRequest is an object used to make API calls in JavaScript. Before the release of ES6 which came with Fetch and libraries like Axios in 2015, it is the only way to call API.
XMLHttpRequests are still used in multiple places because all new and old browsers support this.
- To implement advanced features like request cancellation and progress tracking, XMLHttpRequest is used.
- To maintain old codebases which are written before the announcement of ES6, we use XMLHttpRequest
Example: In this example, XMLHttpRequest is used to make an API call.
JavaScript
const xhttpr = new XMLHttpRequest();
xhttpr.open('GET', 'Api_address', true);
xhttpr.send();
xhttpr.onload = ()=> {
if (xhttpr.status === 200) {
const response = JSON.parse(xhttpr.response);
// Process the response data here
} else {
// Handle error
}
};
Explanation of the above code
Step A: Create an instance of XMLHttpRequest object.
const xhttpr = new XMLHttpRequest();
Step B: Make an open connection with the API endpoint by providing the necessary HTTP method and URL.
xhttpr.open('GET', 'Api_address', true);
Here ‘true’ represents that the request is asynchronous.
Step C: Send the API request
xhttpr.send();
Step D: Create a function onload when the request is completely received or loaded:
xhttpr.onload = ()=> {
if (xhttpr.status === 200) {
const response = JSON.parse(xhttpr.response);
// Process the response data here
} else {
// Handle error
}
};
status – HTTP status code of the response.
Since it is recommended to use newer alternatives like fetch and Axios. But using XMLHttpRequest will give you an understanding of the request-response lifecycle and how HTTP request works. This is how JavaScript API is called using XMLHttpRequest.
2. API Call in JavaScript Using the fetch() method
fetch is a method to call an API in JavaScript. It is used to fetch resources from a server. All modern browsers support the fetch method. It is much easy and simple to use as compared to XMLHttpRequest.
It returns a promise, which contains a single value, either response data or an error. fetch() method fetches resources in an asynchronous manner.
Example: In this example, fetch() is used to make an API call.
JavaScript
fetch('Api_address')
.then(response => {
if (response.ok) {
return response.json(); // Parse the response data as JSON
} else {
throw new Error('API request failed');
}
})
.then(data => {
// Process the response data here
console.log(data); // Example: Logging the data to the console
})
.catch(error => {
// Handle any errors here
console.error(error); // Example: Logging the error to the console
});
Explanation of the above code
Step A: Make an API request to the URL endpoint.
Pass the API URL to the fetch() method to request the API which will return the Promise.
fetch('Api_address')
Step B: Handle the response and parse the data.
Use the .then() method to handle the response. Since the response object has multiple properties and methods to access data, use the appropriate method to parse the data. If the API return JSON data, then use .then() method.
.then(response => {
if (response.ok) {
return response.json(); // Parse the response data as JSON
} else {
throw new Error('API request failed');
}
})
Step C: Handle the parsed data
Make another .then() method to handle the parsed data. Inside that, you can use that data according to your need.
.then(data => {
// Process the response data here
console.log(data); // Example: Logging the data to the console
})
Step D: Handle the Error
To handle errors, use .catch() method at the end of the change.
.catch(error => {
// Handle any errors here
console.error(error); // Example: Logging the error to the console
});
3. API call in JavaScript using Axios
Axios is an open-source library for making HTTP requests to servers. It is a promise-based approach. It supports all modern browsers and is used in real-time applications. It is easy to install using the npm package manager.
It has better error handling than the fetch() method. Axios also does automatic transformation and returns the data in JSON format.
Example: In this example, Axios is used to make an API call.
JavaScript
import axios from 'axios';
axios.get('APIURL')
.then(response => {
// Access the response data
const responseData = response.data;
// Process the response data here
})
.catch(error => {
// Handle any errors
});
Explanation: While sending the HTTP request it will respond to us with the error or the data which is already parsed to JSON format(which is the property of Axios). We can handle data with the .then() method and at the end we will use .catch() method to handle the error.
Note: Here we have to pass the URL and unlike fetch or XMLHttpRequest, we cannot pass the path to the resource.
4. API call in JavaScript Using the jQuery AJAX
jQuery is a library used to make JavaScript programming simple and if you are using it then with the help of the $.ajax() method you can make asynchronous HTTP requests to get data.
To learn more about jQuery AJAX, refer to this article: What is the use of jQuery ajax() method?
Example: In this example, jQuery AJAX is used to make an API call.
JavaScript
$.ajax({
url: 'APIURL',
method: 'GET',
success: function(response) {
const parsedData = JSON.parse(response);
// Process the parsed data here
},
error: function(xhr, status, error) {
// Handle any errors
}
});
Explanation of the above example
Step A: Makinig an API request.
To make an HTTP request use the $.ajax() method and pass a URL inside it by giving the necessary method.
$.ajax({
url: 'APIURL',
method: 'GET',
})
Step B: Handling and Parsing the response.
We will use a callback function success to handle the response and if the response is present we will parse the data to JSON format.
success: function(response) {
const parsedData = JSON.parse(response);
// Process the parsed data here
}
Step C: Handling Error.
To handle an error during the API call, we will use the error callback function.
Here xhr object contains information about the request.
error: function(xhr, status, error) {
// Handle any errors
}
To handle the response, it has two callback functions success and error.
Conclusion
While working with API in JavaScript, you have multiple options to send requests. XMLHttpRequest is the oldest way to call API using creating an instance and handling the response using Event Handler. But after the release of ES6 in 2015, developers were given the option of the fetch() method and Axios library, which are more efficient. Both return Promises which can be handled using the .then()method or async/await method. But in the Axios library, it is easy to handle errors than the fetch() method. However, the choice of method depends on the user preference and the complexity of the project.
For Creating an API, Please refer to this article: Tips for Building an API
Similar Reads
How to Make GET call to an API using Axios in JavaScript?
Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on GitHub. It can be imported in plain JavaScript o
3 min read
How to make ajax call from JavaScript ?
Making an Ajax call from JavaScript means sending an asynchronous request to a server to fetch or send data without reloading the web page. This allows dynamic content updates, enhancing user experience by making the web application more interactive and responsive. In this article, we'll learn about
4 min read
How to make POST call to an API using Axios.js in JavaScript ?
Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on GitHub. It can be imported in plain Javascript o
2 min read
How to connect to an API in JavaScript ?
An API or Application Programming Interface is an intermediary which carries request/response data between the endpoints of a channel. We can visualize an analogy of API to that of a waiter in a restaurant. A typical waiter in a restaurant would welcome you and ask for your order. He/She confirms th
5 min read
What is Call in JavaScript ?
The call method is used to invoke the function with different this object. In JavaScript, this refers to an object. It depends on how we are calling a particular function. In the global scope, this refers to the global object window. The inside function also refers to the global object window. In st
2 min read
How to Make a HTTP Request in JavaScript?
JavaScript has great modules and methods to make HTTP requests that can be used to send or receive data from a server-side resource. There are several approaches to making an HTTP request in JavaScript which are as follows: Table of Content Using fetch APIUsing AjaxUsing fetch APIThe JavaScript fetc
2 min read
JavaScript Function.prototype.call() Method
The call() method allows function calls belonging to one object to be assigned and it is called for a different object. It provides a new value of this to the function. The call() method allows you to write a method once and allows it for inheritance in another object, without rewriting the method f
3 min read
How to make JavaScript wait for a API request to return?
For waiting of an API we must need to use express and nodejs to run the JavaScript code. we will create a simple Node.js-based API using Express that returns a JSON response. This will demonstrate how to make API calls using Async/Await in JavaScript. Create a Simple Express API First, install the r
2 min read
How to Parse JSON Data in JavaScript?
To parse JSON data in JavaScript, you can use the JSON.parse() method. This method converts a JSON string into a JavaScript object, making it easier to work with the data. 1. Parse Simple JSON Strings[GFGTABS] JavaScript //Driver Code Starts{ const jsonS = '{"name": "Rahul",
2 min read
How to use JavaScript in Postman ?
Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. In this tutorial, we will see how to use JavaScript in Postman. Prerequisites:Basic HTTP conceptsKnowledge of REST APIWe will discuss the following two methods to use JavaScript in Postm
3 min read