How to Make an API Call from JavaScript?

Last Updated On Thursday 2nd Jun 2022

JavaScript Rest Api

  • It is important to know about how to make http requests and retrive data from a server.
  • JavaScript Provides some build in objects to interact with the API.

Using XMLHttpRequest()

The XMLHttpRequest object can be used to request data from a web server.

	 const request = new XMLHttpRequest();
    request.open("GET", "https://jsonplaceholder.typicode.com/posts");
    request.send();
    request.onLoad = () => {
       console.log(request);
       if(request.status === 200) {
           console.log(JSON.parse(request.response));
       } else {
           console.log(JSON.parse(request.response));
           console.log(error ${request.status});
       }
    };
	

Using Fetch API()

With the fetch() method. It takes two arguments:

  • A URL or an object representing the request.
  • Optional init object containing the method, headers, body etc.
	fetch(url)
    .then(response => {
        // handle the response
    })
    .catch(error => {
        // handle the error
    });
	

API Call JavaScript

	async function getUsers() {
    let response = await fetch('https://jsonplaceholder.typicode.com/posts');
    let data = await response.josn();
    console.log(data);
}

getUsers().then(res => {
   console.log(res)
})
	

Using Axios

Axios is a promise-based HTTP Client for node.js and the browser.

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
	axios().get('https://jsonplaceholder.typicode.com/posts')
     .then(res => {
        console.log(res)
     }, err =>{
        console.log(err)
     })
	

Using jQuery

	$(document).ready(function(){
   $.ajax({
     url:"https://jsonplaceholder.typicode.com/posts",
     success: function(response){
        console.log(response)
     },
     error: function(error){
        console.log(error)
     },
   });
})
	

References