How to Call Api From Javascript

How to Call Api From Javascript

There are multiple ways to call API from JS. But the primary are three ways.

  1. XMLHttpRequest(Outdated)
  2. fetch
  3. Axios

1.Using Fetch method

Fetch method is available in all the new generation framework such as react js , Vue, Fast js and more.

// Function to make a GET request using fetch
function getData(url) {
    return fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return response.json();
        });
}

// Example usage
var apiUrl = "https://api.example.com/data";
getData(apiUrl)
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error("Error:", error);
    });

2.Using Axios method

Axios method is available in all the new generation framework such as react js , Vue, Fast js and more.

   function getData(url) {
        return axios.get(url)
            .then(response => response.data)
            .catch(error => {
                throw new Error(`Axios error: ${error.message}`);
            });
    }

    // Example usage
    var apiUrl = "https://api.example.com/data";
    getData(apiUrl)
        .then(data => {
            console.log(data);
        })
        .catch(error => {
            console.error("Error:", error);
        });

Using Axios is considered more advanced as it simplifies the code significantly and provides built-in features for handling errors and processing responses. The choice of method depends on the developer’s preference and project requirements. The provided examples cover the GET request; for other HTTP methods, you would adjust the method and payload accordingly.

The best practices are:

Step 1: Understanding the Fundamentals

The advanced developer, having gained experience in web development, starts by understanding the fundamentals of RESTful APIs. They grasp concepts like HTTP methods (GET, POST, PUT, DELETE), status codes, request and response structures, and the significance of headers.

Step 2: Choosing the Right Tool for the Job

Rather than blindly copying code snippets, the advanced developer carefully selects the appropriate tool for making API calls. They might opt for the fetch API for its simplicity, or if the project requires broader compatibility, they might consider using a library like Axios.

Step 3: Building a Wrapper Function

To enhance code maintainability and reusability, the advanced developer builds a wrapper function around the API calls. This function abstracts away the complexity, making it easier to manage endpoints, headers, and error handling consistently throughout the application.

Step 4: Handling Errors Gracefully

Understanding that not all API calls will be successful, the advanced developer implements robust error handling. They consider HTTP status codes, network errors, and unexpected responses, providing meaningful feedback to users and logging detailed information for debugging.

Step 5: Embracing Asynchronous JavaScript

The advanced developer embraces the asynchronous nature of JavaScript by using Promises or async/await syntax. This allows them to handle multiple API calls concurrently without blocking the main thread, improving the application’s responsiveness.

Join Our Newsletter

Get to know whats happening with the API instantly in your inbox. No spam for sure.