4 Ways to make api call in JavaScript
Published: 2023-09-10 10:51:49

In JavaScript, there are multiple ways to make API calls. Here are some commonly used methods and techniques:



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h71lo3z4a1npt5bzls1i.jpg)
<head>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8153971012189888"
     crossorigin="anonymous"></script>
</head>

**<u>1. XMLHttpRequest:</u>** This is a built-in object in JavaScript that allows you to make asynchronous HTTP requests. It’s the traditional way of making API calls in JavaScript. However, it has a complex API and is often replaced by more modern approaches.

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true);
xhr.onreadystatechange = function() {
 if (xhr.readyState === 4 && xhr.status === 200) {
 var response = JSON.parse(xhr.responseText);
 // Process the response data here
 }
};
xhr.send();
By default, we receive the response in a string format. We’ll need to parse it into JSON.

XMLHttpRequest was deprecated in ES 6 by the introduction of fetch. But XMLHttpRequest is still useful when you need to work with old browsers and don’t want polyfills.

**<u>2. Fetch API:</u>** This is a newer and more powerful API for making API calls. It provides a simpler and more flexible way to handle requests and responses.

fetch('https://jsonplaceholder.typicode.com/posts')
 .then(function(response) {
 if (response.ok) {
 return response.json();
 }
 throw new Error('Network response was not ok.');
 })
 .then(function(data) {
 // Process the response data here
 })
 .catch(function(error) {
 // Handle errors here
 });
The fetch API is very powerful. We can easily send AJAX requests using the browser fetch API.

**<u>3. Axios:</u>** Axios is a popular third-party library for making HTTP requests in JavaScript. It supports both browser and Node.js environments and provides a simple and elegant API.

How to install axios

npm install axios
The easiest way to include Axios is by using external CDN in the HTML File

```

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
```
Axios provides the following advantages:

Axios performs automatic transformations and returns the data in JSON format.
Better error handling.
Axios has a wide range of supported browsers.
axios.get('https://jsonplaceholder.typicode.com/posts')
 .then(function(response) {
 // Process the response data here
 })
 .catch(function(error) {
 // Handle errors here
 });
**<u>4. jQuery AJAX:</u>** If you’re using the jQuery library, you can use its AJAX methods to make API calls. It simplifies the process and provides additional features like JSONP support.

JQuery has many methods to handle asynchronous HTTP requests. In order to use jQuery, we need to include the source file of jQuery. The $.ajax() method is used to make the HTTP request.

Jquery CDN :

```

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>
<body>
    <script>
        $.ajax({
            url: 'https://jsonplaceholder.typicode.com/posts',
            method: 'GET',
            success: function(response) {
            // Process the response data here
            },
            error: function(jqXHR, textStatus, errorThrown) {
            // Handle errors here
            }
});
    </script>
</body>
</html>
```
The $.ajax method takes many parameters, some that are required and others that are optional. It contains two callback functions success and error to handle the response received.

Conclusion :

These are some of the common ways to make API calls in JavaScript. Each method has its advantages and may be more suitable depending on your specific requirements and the environment you’re working in.

Most of the real-time applications use Axios to make HTTP Requests. Axios is very easy to use and is an open-source library for making HTTP requests. And those are the most popular ways to make HTTP requests.