API stands for Application Programming Interface. It is a set of rules and protocols that allow one software application to interact with another. An API is a service designed for applications that request data or specific functions from servers.
To allow other applications to access specific functionalities and data within our system, developers create APIs and provide endpoints for interaction. When working with JavaScript, it’s a common practice to use these APIs to retrieve data from or send requests to a server, enabling seamless integration and communication between different systems.
4 Ways to Make an API Call in JavaScript
1. API Call in JavaScript Using XMLHttpRequest
XMLHttpRequest is an object in JavaScript used for making API calls. Prior to the release of ES6 in 2015, which introduced the Fetch API and libraries like Axios, XMLHttpRequest was the primary method for handling API requests. Despite the newer alternatives, XMLHttpRequest remains widely used due to its compatibility with both modern and older browsers. To maintain old codebases which are written before the announcement of ES6, we use XMLHttpRequest.
Example
const xhttpr = new XMLHttpRequest();
xhttpr.open('GET', 'apiUrl', true);
xhttpr.send();
xhttpr.onload = ()=> {
if (xhttpr.status === 200) {
const response = JSON.parse(xhttpr.response);
// Process the response data here
} else {
// Handle error
}
};
In the above example, I have created an instance of XMLHttpRequest object first and then open the connection with API endpoint.
xhttpr.open(‘GET’, ‘apiUrl’, true); in this code snippet, the true represents that the request is asynchronous.
After, create a function onload when the request is completely received or loaded.
While it is recommended to use modern alternatives like Fetch and Axios for making API calls, working with XMLHttpRequest provides valuable insights into the request-response lifecycle and the workings of HTTP requests. This is an example of how to call a JavaScript API using XMLHttpRequest.
2. API Call in JavaScript Using the fetch() method
The fetch method in JavaScript is used to make network requests and retrieve resources from a server. Unlike XMLHttpRequest, fetch is simpler and more intuitive to use. It works across all modern browsers and provides a more streamlined approach for handling network requests.
When you use fetch, it returns a promise that resolves to the response of the request. This promise will either resolve with the response data if the request is successful or with an error if something goes wrong. The fetch method operates asynchronously, allowing you to handle network requests in a non-blocking manner.
Example:
fetch('apiUrl')
.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
});
In the example above, pass the API endpoint as an argument to the fetch function. fetch will handle the response and return the data. If any errors occur while fetching the API endpoint, they will be caught and handled in the catch block.
3. API call in JavaScript using Axios
Axios is a popular open-source library designed for making HTTP requests to servers. It operates on a promise-based model and is compatible with all modern browsers, making it a great choice for real-time applications. Installation is straightforward through the npm package manager.
One of Axios’s advantages over the fetch() method is its enhanced error handling capabilities. Additionally, Axios automatically transforms response data and returns it in JSON format, streamlining the process of working with API responses.
Example:
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
});
When you send an HTTP request using Axios, it returns either the parsed JSON data or an error. The data is automatically parsed into JSON format, thanks to Axios’s built-in functionality. You can manage the response data with the .then() method and handle any errors with the .catch() method at the end.
4. API call in JavaScript Using the jQuery AJAX
jQuery is a library that simplifies JavaScript programming. If you’re using jQuery, you can make asynchronous HTTP requests to retrieve data using the $.ajax() method. This method lets you easily send and receive data from a server without reloading the page.
Example:
$.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
}
});
To perform an HTTP request, use the $.ajax() method and provide the URL along with the required HTTP method.
We’ll use a success callback function to process the response. If the response is available, we’ll convert the data into JSON format.
To manage errors during the API call, we’ll utilize the error callback function. The xhr object within this function provides details about the request.
You may also like this:
Conclusion:
When working with APIs in JavaScript, you have several options for sending requests. XMLHttpRequest is the traditional method, requiring the creation of an instance and handling responses via event handlers. With the advent of ES6 in 2015, fetch() and Axios emerged as more modern and efficient alternatives. Both of these methods return Promises that can be managed using the .then() method or async/await. Axios provides more straightforward error handling compared to fetch(). Ultimately, the choice between these methods depends on personal preference and the complexity of the project.