How to make API calls in JavaScript?

An API call is often required while trying to access an external library or performing database operations in the project. We can make API calls in JavaScript using the Fetch API method or XMLHttpRequest. These calls help retrieve dynamic data from a database or server. Let’s dive into the details on how to make API calls in JavaScript.

API calls in JavaScript

Fetch API

Fetch is the recommended way to retrieve data from an API. It is a modern, and promise-based method to make API requests, and is supported by modern browsers. fetch is a built-in JavaScript function in modern browsers that can easily make network requests and handle the response. It works in a similar way to XMLHttpRequest but is more straightforward. Consider the code snippet below.

fetch('https://api.scratchcoding.dev/data')
  .then(response => response.json())
  .then(data => {
    // Process data received from API
    console.log(data);
  })
  .catch(error => {
    // Handle errors if the API call fails
    console.error('Error fetching data:', error);
  });

You can directly call the. API URL in the fetch method as shown above, then handle the response. The response is received in JSON format. Fetch may not be supported by old browsers but is always recommended for new and modern browsers.

XMLHttpRequest

XMLHttpRequest is an object. in JavaScript that can send HTTP requests and receive responses accordingly. It is a built-in browser object and enables us to make HTTP requests in JavaScript. The response from the XMLHttpRequest object is received in string format, we can later parse it to JSON. Consider the code snippet below.

// Making a GET request
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.scratchcoding.dev/data', true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
    const data = JSON.parse(xhr.responseText);
    // Process response received
    console.log(data);
  } else if (xhr.readyState === XMLHttpRequest.DONE) {
    // Handle errors if the API call fails
    console.error('Error fetching data:', xhr.status);
  }
};
xhr.send();

The XMLHttpRequest. is supported by most browsers, but it is not recommended to use. As the new version of JavaScript, ES6 doesn’t support it. It is an older way to make API requests in JavaScript and is. not recommended to use for new JavaScript projects.