How to call API in JavaScript


API calling is a very common task in web development. If you want to develop something that uses data from another website, you need to call their API.

For example, if you want to develop a website that shows the current weather of a city, in that case, you need to find a website that provides weather data and then call their API to get the data.

There are many websites that provide free APIs, you can use them to develop your own website or application.

In this tutorial, we will learn how to call an API in JavaScript in various ways.


1. Using XMLHttpRequest

XMLHttpRequest is an old way to make an asynchronous HTTP request in JavaScript. It is supported by all the browsers.

You can use it to call an API in JavaScript. Here is how you can do it.

Example

// Create a new XMLHttpRequest object
let xhr = new XMLHttpRequest();

// Configure it: GET-request for the URL /api/...
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts');

// Send the request over the network
xhr.send();

// This will be called after the response is received
xhr.onload = function() {
  if (xhr.status == 200) {
    // If the response is successful, show the result
    alert(`Done, got ${xhr.response.length} bytes`);
  } else {
    // If there was an error, show what went wrong
    alert(`Error ${xhr.status} ${xhr.statusText}`);
  }
};

Code Explanation:

  1. Create a new XMLHttpRequest object
  2. Configure the request using the open() method. The open() method accepts two arguments, the first one is the HTTP method and the second one is the URL of the API.
  3. Send the request using the send() method.
  4. After the response is received, the onload() method is called. The onload() method is called when the response is received successfully.
  5. Inside the onload() method, we check the status of the response. If the status is 200, it means the response is successful and we can show the result to the user.

2. Using fetch()

fetch() is a powerful built-in JavaScript method that provides an easy way to fetch resources across the network.

To use this method, pass the URL of the API to the fetch() method. It then returns a Promise which resolves to the Response object.

Here is an example to show this method in action.

Example

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(data => alert(`Done, got ${data.length} bytes`))
  .catch(error => alert(error.message));

3. Using async/await

async/await is another way you can use to call APIs. It is a modern way to handle asynchronous code in JavaScript.

It makes the code look synchronous, but it is still asynchronous. It is supported by all the modern browsers.

Here is an example to show how to call an API using async/await.

Example

async function getData() {
  try {
    let response = await fetch('https://jsonplaceholder.typicode.com/posts');
    let data = await response.json();
    alert(`Done, got ${data.length} bytes`);
  } catch(error) {
    alert(error.message);
  }
}

getData();

Now let's see how to call an API using some popular JavaScript libraries.

4. Using jQuery

jQuery is the most popular JavaScript library. Among a lots and lots of features, it provides an easy way to make an HTTP request.

Here is an example to show how to call an API using jQuery.

$.ajax({
  url: 'https://jsonplaceholder.typicode.com/posts',
  type: 'GET',
  success: function(data) {
    alert(`Done, got ${data.length} bytes`);
  },
  error: function(error) {
    alert(error.message);
  }
});

5. Using axios

axios is another popular JavaScript library that is used to make HTTP requests. To use this library, you need to install it first.

Here is how you can install it using npm.

npm install axios

Or you can use the CDN link to include it in your HTML file.

It provides a method called get() to make a GET request.

Pass the URL of the API to the get() method. It then returns a Promise which you can use to handle the response.

axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(response => alert(`Done, got ${response.data.length} bytes`))
  .catch(error => alert(error.message));

Conclusion

Among all the methods we have discussed, the fetch() method is the most popular one for calling APIs in JavaScript.

You can use any of the methods we have discussed in this tutorial based on your requirements.

Happy Coding!