Have you tried all API calls in JavaScript? Here are 4 ways to do it
Tags: webdev, javascript, api, programming
Published: 2024-07-16 21:31:52

> API calls are a key part of modern web development. JavaScript offers several ways to accomplish this task, each with its own advantages and disadvantages. This article will introduce you to four main methods of making API calls in JavaScript that you can use in your projects.

## XMLHttpRequest (XHR)

**XMLHttpRequest (XHR)** is a traditional way to call APIs, supported in all browser versions. This method is reliable and widely used, although its syntax can sometimes be harder to read and maintain.

```
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            console.log(JSON.parse(xhr.responseText)); // Parse and log the response data
        } else {
            console.error('Error:', xhr.statusText); // Log any errors
        }
    }
};
xhr.send();
```

---

## Fetch API

**Fetch API** is a more modern and simpler way to make API calls, based on promises. It supports asynchronous operations and is easy to extend using async and await.

```
fetch("https://api.example.com/data")
    .then(response => response.json())
    .then(data => console.log(data)) // Log the response data
    .catch(error => console.error('Error:', error)); // Log any errors
```

**Using async and await.**

```
async function fetchData() {
    try {
        const response = await fetch("https://api.example.com/data");
        const data = await response.json();
        console.log(data); // Log the response data
    } catch (error) {
        console.error('Error:', error); // Log any errors
    }
}
fetchData();
```

---

## Axios

**Axios** is a popular library for HTTP requests that provides a simple and consistent interface for making API calls. It needs to be installed first using npm or yarn.
`npm install axios`
or
`yarn add axios`

Then you can use Axios for making API calls:

```
const axios = require('axios');

axios.get("https://api.example.com/data")
    .then(response => {
        console.log(response.data); // Log the response data
    })
    .catch(error => {
        console.error('Error:', error); // Log any errors
    });
```
Using async and await:

```
async function fetchData() {
    try {
        const response = await axios.get("https://api.example.com/data");
        console.log(response.data); // Log the response data
    } catch (error) {
        console.error('Error:', error); // Log any errors
    }
}
fetchData();
```

---

## jQuery AJAX

**jQuery AJAX** is a method for making API calls using the jQuery library. Although jQuery is less commonly used today, it still appears in older projects.

```
<!-- Include jQuery library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
$(document).ready(function() {
    $.ajax({
        url: "https://api.example.com/data",
        method: "GET",
        success: function(data) {
            console.log(data); // Log the response data
        },
        error: function(error) {
            console.error('Error:', error); // Log any errors
        }
    });
});
</script>
```

---

_Source photo:_
RAKOZY, Greg. Website design books. Online. In: Unsplash. 2016. Available from: https://unsplash.com/photos/html-css-book-vw3Ahg4x1tY. [cit. 2024-07-16].