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

XML HTTP Request

JavaScript
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))
}

XML HTTP Request

Fetch API

JavaScript
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 Installation (Using Package Manager)

JavaScript
npm install axios

OR

yarn add axios

and include it in the HTML file like

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

Using CDN

JavaScript
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
JavaScript
<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

jQuery Ajax

Attach jQuery inside the HTML file using CDN

JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
JavaScript
<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.