DEV Community

Cover image for Have you tried all API calls in JavaScript? Here are 4 ways to do it
Tomas Stveracek
Tomas Stveracek

Posted on

Have you tried all API calls in JavaScript? Here are 4 ways to do it

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();
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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
    });
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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].

Top comments (0)