How to make an API call in JavaScript

In this article, I will guide you on how to make API calls in Javascript.

So, let's get started,

JavaScript provides a few built-in methods and external open-source libraries to create and interact with the API. A few possible methods to make an API call in JavaScript are

  • XMLHttpRequest
  • Fetch
  • Using Axios library
  • jQuery AJAX

XML HTTP Request

var xmlRequest = new XMLHttpRequest();

xmlRequest.open('GET', 'https://api.github.com/users/vyelve');
xmlRequest.send();

xmlRequest.onload = () => {
  if (xmlRequest.status === 200) {
    console.log('Request successful');
  }
  else {
    console.log('Error occurred!');
  }

  console.log(JSON.parse(xmlRequest.response))
}
  • It receives a response in string format that needs to be parsed in JSON format (JSON.parse(XMLRequest.response)).
  • It is a built-in browser object to create HTTP requests & is deprecated with the introduction of fetch in ES 6. Still, it is used when we work with older browsers.

XML HTTP Request

Fetch API

fetch('https://api.github.com/users/vyelve')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

Fetch API

for more details refer to my article on fetching API

Axios

  • Axios is an open-source library for making HTTP requests with several great features.
  • Axios works in both Node.js and browsers and is a promise-based (asynchronous) HTTP client, which is even used in frameworks like Angular & React.

Axios Installation (Using Package Manager)

npm install axios

OR

yarn add axios

and include it in the HTML file like

<script src="./node_modules/axios/dist/axios.min.js"></script>

Using CDN

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios.get("https://api.github.com/users/vyelve")
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  })
</script>

Axios

Pros of Axios

  • Better and easier error handling and has a wide range of browser support.
  • Axios automatically performs JSON parsing and returns data in JSON format.

jQuery Ajax

Attach jQuery inside the HTML file using CDN

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
  $.ajax({
    url: "https://api.github.com/users/vyelve",
    type: "GET",
    success: function (result) {
      console.log(result);
    },
    error: function (error) {
      console.log(error);
    }
  })
})
</script>

jQuery Ajax

Summary

In this article, I have tried to cover how to make API calls from JavaScript.