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

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

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)

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

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.