DEV Community

loading...
Cover image for Four Ways To Make An API Calls In Javascript

Four Ways To Make An API Calls In Javascript

anuradha9712 profile image Anuradha Aggarwal Originally published at anuradha.hashnode.dev ・2 min read

Hello developers!! In this post, we'll discuss various ways to make an API call for your next project.

🔎 XML HTTP Request

  • All modern browsers support the XMLHttpRequest object to request data from a server.
  • It works on the oldest browsers as well as on new ones.
  • It was deprecated in ES6 but is still widely used.
var request = new XMLHttpRequest();
request.open('GET', 'https://api.github.com/users/anuradha9712');
request.send();
request.onload = ()=>{
    console.log(JSON.parse(request.response));
}

Enter fullscreen mode Exit fullscreen mode

🔎 Fetch

  • The Fetch API provides an interface for fetching resources (including across the network) in an asynchronous manner.
  • It returns a Promise
  • It is an object which contains a single value either a Response or an Error that occurred.
  • .then() tells the program what to do once Promise is completed.
fetch('https://api.github.com/users/anuradha9712')
.then(response =>{
    return response.json();
}).then(data =>{
    console.log(data);
})
Enter fullscreen mode Exit fullscreen mode

🔎 Axios

  • It is an open-source library for making HTTP requests.
  • It works on both Browsers and Node js
  • It can be included in an HTML file by using an external CDN
  • It also returns promises like fetch API
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Enter fullscreen mode Exit fullscreen mode
axios.get('https://api.github.com/users/anuradha9712')
.then(response =>{
    console.log(response.data)
})
Enter fullscreen mode Exit fullscreen mode

🔎 jQuery AJAX

  • It performs asynchronous HTTP requests.
  • Uses $.ajax() method to make the requests.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Enter fullscreen mode Exit fullscreen mode
$(document).ready(function(){
    $.ajax({
        url: "https://api.github.com/users/anuradha9712",
        type: "GET",
        success: function(result){
            console.log(result);
        }
    })
})
Enter fullscreen mode Exit fullscreen mode

Wrap Up!!

Thank you for your time!! Let's connect to learn and grow together.

LinkedIn Twitter
Instagram

Buy-me-a-coffee

Discussion (2)

pic
Editor guide
Collapse
aminnairi profile image
Amin

So really two ways then, isn't it?

Collapse
ianwijma profile image
Ian Wijma

I personally don't think its a great idea to include jQuery JUST for $.ajax, if you really want to use a library I'd recommend axios, like you described.