The Wayback Machine - https://web.archive.org/web/20240624003214/https://www.geeksforgeeks.org/ways-to-make-an-api-call-in-javascript/
Open In App

4 Ways to Make an API Call in JavaScript

Last Updated : 07 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

How to Make an API Call in JavaScript

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

FAQs

1. What are the different ways to make an API call in JavaScript?

1. Using XMLHttpRequest
2. fetch() method
3. Using Axios library
4. Using jQuery AJAX

2. What are the different types of API?

There are 4 different types of APIs used in web services:

1. Public
2. Partner
3. Private
4. Composite

3. What are API call methods?

An API call is a process of sending a request to API by a user application and that API retrieves the requested data from the server and sends the response to the user application.



Similar Reads

Call by Value Vs Call by Reference in JavaScript
Call by Value: In this method, values of actual parameters are copied to the function’s formal parameters, and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in the actual parameters of the caller. Suppose there is a variable named “a”. Now, we store a primitive value(boo
3 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 or with any library accordingly. The following scri
2 min read
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 or with any library accordingly. There are two meth
3 min read
Program to swap two integer parameters using call by value & call by address in PHP ?
Call by value: In call by value, we will send the value from the calling function to the called function. The values of the calling function arguments are directly copied to the corresponding arguments of the called function. If any modification is done on the arguments of the called function, it will not be effected on the arguments of the calling
3 min read
How to make ajax call from JavaScript ?
Ajax is a powerful tool in web development for asynchronous communication with servers. With Ajax, you can fetch data from the server and update your webpage without interrupting what your user sees. It's a basic concept in programming. In this article, we'll learn about three ways to make Ajax calls in JavaScript: Using the XMLHttpRequest objectUs
4 min read
How to call an API continuously from server side itself in Node.js/Express.js ?
Calling an API endpoint is the core functionality of modern internet technology. Usually, we call API from the browser. Sometimes we need to call API endpoint from the server itself to fetch data, load dependencies, etc. There are many ways to call API from NodeJS server itself, depending on the abstraction level that you want to use. The simplest
3 min read
REST API Call to Get Location Details in Vue.js
In this article, we will know the REST API call to get the location details in VueJS, along with understanding its implementation through the examples. VueJS is one of the best frameworks for JavaScript like ReactJS. The VueJS is used to design the user interface layer, it is easy to pick up for any developer. It is compatible with other libraries
7 min read
How to send API call before page reload or close using ReactJS ?
To send an API call before the page reloads or closes using React JS we have to link or define a function when the page unloads. The page unloading happens just before the page is closed or tries to reload. PrerequisitesReact JSHTML DOM onbeforeinload eventApproachWe will use some listeners like "beforeupload" and "upload", which trigger a function
2 min read
How to Delay a JavaScript Function Call using JavaScript ?
When we want to call a function after a described amount of time, we use a delay function in JavaScript. There are several ways to delay the execution of a function. This can be useful for various purposes, such as creating animations, implementing debounce in search inputs, or simply delaying an action until a certain condition is met. Table of Co
2 min read
How to make a JSON call using jQuery ?
Use the getJSON() function in jQuery to load JSON data. The getJSON() function uses a GET HTTP request to retrieve JSON-encoded data from the server. In this article, we will learn about the jQuery getJSON() function and its implementation through examples. Syntax: $(selector).getJSON(url, data, success(data, status, xhr)) Parameters: This method a
3 min read
three90RightbarBannerImg