Home » How to call an API using JavaScript?
JavaScript Banner

How to call an API using JavaScript?

Introduction:

In a large-scale web development environment, the ability to communicate with external applications and retrieve data is essential. Application Programming Interfaces (APIs) play an important role in facilitating this communication. In this blog post, we’ll explore How to call an API using JavaScript, a popular scripting language for web development.

What is API?

API stands for Application Programming Interface. It is a set of rules and protocols that allows one software application to interact with another. This interaction can involve the use of web services, libraries, or operating systems. APIs enable integration of systems, fostering application development leveraging functionalities from diverse software for seamless and efficient operations.

The RESTful API, adhering to Representational State Transfer (REST) constraints, is a common type in the realm of APIs. This style emphasizes stateless client-server communication and the use of standard HTTP methods. Overall, APIs facilitate seamless communication and interoperability, playing a crucial role in modern software development between diverse applications and systems.

There are four ways to call Api

  1. API Call Using XMLHttpRequest
  2. API Call Using Fetch API
  3. API Call Using AXIOS
  4. API Call Using Jquery

In this blog we are using API Link is here : https://jsonplaceholder.typicode.com/todos

1. API Call Using XMLHttpRequest

XMLHttpRequest (XHR) is an API in the form of an object whose methods transfer data between a web browser and a web server. It can be used to make requests to the server without having to refresh the entire page. The XHR object can be used to retrieve any type of data, not just XML, and it is supported across all modern web browsers. 

To call an API using XMLHttpRequest in JavaScript, you can follow these steps:

1. Create an XMLHttpRequest object: First, create an instance of the XMLHttpRequest object using the following line of code:

const xhr = new XMLHttpRequest();

2. Open the request: Use the open() method to open the request. You need to pass the HTTP method and the URL of the API endpoint as arguments:

xhr.open('GET', 'apiUrl');

3. Set the response type: Set the response type to JSON using the responseType property:

xhr.responseType = 'json';

4. Send the request: Use the send() method to send the request to the server:

xhr.send();

5. Handle the response: Use the onload event listener to handle the response. The response data is available in the response property of the XMLHttpRequest object:

xhr.onload = function() {
  const data = xhr.response;
  // Handle the data
};

6. Handle errors: Use the onerror event listener to handle errors that may occur during the network request:

xhr.onerror = function() {
  // Handle the error
};

Here’s a complete example of using XMLHttpRequest to call a REST API:

// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Configure the GET request
xhr.open("GET", "https://jsonplaceholder.typicode.com/todos", true);

// Define the onload callback function to handle the response
xhr.onload = function() {
  // Check if the request was successful
  if (xhr.status >= 200 && xhr.status < 300) {
    // Parse the XML response
    var xmlResponse = xhr.response;
    // Handle the XML response as needed
    console.log(xmlResponse);
  } else {
    // Handle any errors
    console.error('Request failed with status: ' + xhr.status);
  }
};

// Send the request
xhr.send();

Ouptut:

API Call Using XMLHttpRequest

Remember that XMLHttpRequest is asynchronous, so you need to use async/await or then() methods to handle the resolution and rejection of the promise.

2. API Call Using Fetch API

The Fetch API is a JavaScript interface that provides a simple and logical way to fetch resources asynchronously across the network. It is promise-based and offers better performance compared to XMLHttpRequest. To make an API call using the Fetch API, you can follow these steps:

1. Create a fetch request: The basic syntax for a fetch request is fetch(url). You can also provide additional options, such as request method, headers, and body, using the fetch() function with two arguments.

fetch('url')
  .then(response => {
    // Handle the response
  })
  .then(data => {
    // Handle the data
  })
  .catch(error => {
    // Handle the error
  });

2. Handle the response: The fetch() method returns a promise that resolves into a response object. You can extract the JSON body content from the response using the json() method.

fetch('url')
  .then(response => response.json())
  .then(data => {
    // Handle the data
  })
  .catch(error => {
    // Handle the error
  });

3. Handle errors: Error handling is crucial for making robust applications. The Fetch API provides a convenient way to catch and handle errors that may occur during a network request.

fetch('url')
  .then(response => response.json())
  .then(data => {
    // Handle the data
  })
  .catch(error => {
    // Handle the error
  });

Here’s an example of making a GET request to an API using the Fetch API:

fetch('apiUrl')
  .then(response => response.json())
  .then(data => {
    // Handle the data
  })
  .catch(error => {
    // Handle the error
  });

For handling POST requests, you can pass the method: 'POST' option along with the request body in the fetch() function:

// Making a GET request using Fetch API
fetch('https://jsonplaceholder.typicode.com/todos')
  .then(response => {
    // Check if the request was successful (status code 200)
    
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    // Parse the response JSON
    return response.json();
  })
  .then(data => {
    // Handle the parsed data
    
    console.log(data);
  })
  .catch(error => {
    // Handle errors during the fetch
    console.error('Fetch error:', error);
  });

Output:

API Call Using Fetch API

Remember that the Fetch API is asynchronous, so you need to use async/await or then () methods to handle the resolution and rejection of the promise.

3. API Call Using AXIOS

Axios is a popular HTTP client for making API calls in JavaScript applications. It is promise-based and can be used with various HTTP methods, such as GET, POST, PUT, and DELETE. To call an API using Axios in JavaScript, follow these steps:

1. Import CDN file of Axios: First, import the Axios library in your HTML file using the following line of code:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

2. Make a GET request: To make a GET request using Axios, use the axios.get() method. Here’s an example:

axios.get('apiUrl')
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle the error
  });

3. Make a POST request: To make a POST request using Axios, use the axios.post() method. You need to pass the URL and the data object as arguments:

axios.post('apiUrl', {
  key1: 'value1',
  key2: 'value2',
})
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle the error
  });

4. Handle the response: Axios returns a promise that resolves to a response object. You can extract the data from the response using the data property:

axios.get('apiUrl')
  .then(response => {
    const data = response.data;
    // Handle the data
  })
  .catch(error => {
    // Handle the error
  });

5. Error handling: Always handle errors that may occur during network requests. Axios provides a convenient way to catch and handle errors:

axios.get('apiUrl')
  .then(response => {
    const data = response.data;
    // Handle the data
  })
  .catch(error => {
    // Handle the error
  });

Here’s a complete example of using Axios to call a REST API:

// Include Axios library in your project
// You can install it using npm or include it via a CDN in your HTML file

// Make a GET request using Axios


axios.get('https://jsonplaceholder.typicode.com/todos')
  .then(response => {
    // Handle the response data
    console.log(response.data);
  })
  .catch(error => {
    // Handle errors during the request
    console.error('Axios error:', error);
  });

Output:

API Call Using axios API

Remember that Axios is promise-based, so you need to use async/await or then () methods to handle the resolution and rejection of the promise.

4. API Call Using Jquery

To call an API using jQuery in JavaScript, you can use the $.ajax() function or the $.getJSON() function. Here’s a step-by-step guide on how to call an API using jQuery:

1. Include jQuery: First, include the jQuery library in your HTML file using the following line of code:

You can include jquey library for this link: https://developers.google.com/speed/libraries

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

2. Make a GET request: To make a GET request using jQuery, use the $.getJSON() function. Here’s an example:

$.getJSON('apiUrl', function(data) {
  // Handle the data
})
.fail(function(jqXHR, textStatus, errorThrown) {
  // Handle the error
});

3. Make a POST request: To make a POST request using jQuery, use the $.post() function. You need to pass the URL and the data object as arguments:

$.post('apiUrl', {
  key1: 'value1',
  key2: 'value2',
})
.done(function(data) {
  // Handle the data
})
.fail(function(jqXHR, textStatus, errorThrown) {
  // Handle the error
});

4. Handle the response: jQuery returns a promise that resolves to a response object. You can extract the data from the response using the data property:

$.getJSON('apiUrl', function(data) {
  const data = jQuery.parseJSON(data);
  // Handle the data
})
.fail(function(jqXHR, textStatus, errorThrown) {
  // Handle the error
});

5. Error handling: Always handle errors that may occur during network requests. jQuery provides a convenient way to catch and handle errors:

$.getJSON('apiUrl', function(data) {
  const data = jQuery.parseJSON(data);
  // Handle the data
})
.fail(function(jqXHR, textStatus, errorThrown) {
  // Handle the error
});

Here’s a complete example of using jQuery to call a REST API:

// Make a GET request using jQuery
$.ajax({
    url: 'https://jsonplaceholder.typicode.com/todos',
    method: 'GET',
    success: function(data) {
      // Handle the response data
      console.log(data);
    },
    error: function(error) {
      // Handle errors during the request
      console.error('jQuery Ajax error:', error);
    }
  }); 

Output:

API Call Using jquery API

Remember that jQuery is asynchronous, so you need to use async/await or then() methods to handle the resolution and rejection of the promise.

Conclusion:

In this comprehensive guide, we explored the basics of calling APIs with JavaScript. Confidently add API calls to your JavaScript applications by understanding the role of APIs, using Fetch API, and handling async/await.

Remember, this is just the tip of the iceberg in the web development area. Continuing API exploration introduces authentication, error handling nuances specific to the mechanisms, providing a deeper understanding of API intricacies. Prepared with knowledge from this guide, you possess a solid foundation to build on in your web development journey. Happy coding!

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *