Making API Call in JavaScript

Making API Call in JavaScript

Table of contents

No heading

No headings in the article.

In a typical web application, the frontend and backend communicate through APIs (Application Programming Interfaces). APIs are used to streamline communication and data exchange between different systems. It specifies how the communication should take place, what data should be shared, and what actions can be performed on the shared data. To bring more clarity, here are key points on what usually happens on a typical web application making API calls:

  1. The user interacts with the front end (e.g., by clicking a button, filling out a form, etc.).

  2. The front end sends a request to the backend API, specifying what action it wants to perform (e.g., "get user data," "create a new record," etc.).

  3. The backend API receives the request, processes it, and sends back a response to the front end, which could be data, an error message, or a success message.

  4. The front end receives the response and updates the UI accordingly (e.g., by displaying the data, showing an error message, etc.).

For instance, let us take a reference of a simple Weather app. A weather app typically works by making API calls to a weather data provider, such as OpenWeatherMap or AccuWeather. Here's how the process works:

  1. The user opens the weather app and enters a location (e.g., city, zip code, or GPS coordinates).

  2. The app sends an HTTP request to the weather data provider's API, specifying the location and any other parameters (e.g., temperature units, language, etc.).

  3. The weather data provider's API receives the request, processes it, and retrieves the current weather data for the specified location.

  4. The API sends back a JSON response containing the weather data, such as temperature, humidity, wind speed, and conditions (e.g., sunny, cloudy, rainy, etc.).

  5. The weather app receives the JSON response and parses it to extract the relevant data.

  6. The app displays the weather data to the user in a user-friendly format, such as a dashboard, a map, or a widget.

Overall, the weather app relies heavily on the weather data provider's API to provide accurate and timely weather information to the user, and the app's success depends on the quality of the API and the app's ability to consume and display the data.

To make the API call, the weather app needs to use a programming language and a framework or library that can handle HTTP requests and JSON parsing, such as JavaScript and jQuery for web apps, or Swift and Alamofire for iOS apps. The app also needs to handle errors and exceptions, such as network connectivity issues, invalid location input, or API rate limits.

This article discusses on a general overview of how API calls are made and response is consumed using the two mostly used methods available in Javascript (XHR object and fetch API).

Consuming APIs using JavaScript involves the following general process:

  1. Understanding the API: Before you start using any API, it is important to read the documentation to understand how it works and what endpoints are available. This information will help you structure your requests correctly.

  2. Sending HTTP Requests: To use an API in JavaScript, you need to send HTTP requests to the API endpoints. JavaScript provides several ways to send HTTP requests, including the built-in XMLHttpRequest object, the fetch method, and third-party libraries like Axios and jQuery.

  3. Handling Responses: After sending a request, the API will respond with data in a specified format, usually JSON or XML. You need to parse this data to extract the information you need and use it in your application.

  4. Implementing Error Handling: APIs can return errors for various reasons, such as invalid requests, authentication issues, or server errors. It is important to implement error handling to inform users of any issues and handle them gracefully.

Now, let us dive into how we can achieve it for the web using Javascript. There are several ways to make API calls in JavaScript. Here are some common methods:

  1. XMLHttpRequest (XHR) object:

    The XMLHttpRequest object is a built-in browser object that allows you to make HTTP requests to a server. It can be used to send both GET and POST requests and is supported in all modern browsers. However, it requires more code to implement than newer approaches. The major steps involved are:

    1. Create an XHR object : The first step is to create an instance of the XHR object using the XMLHttpRequest() constructor.

       const xhr = new XMLHttpRequest();
      
    2. Open a connection : Next, you need to open a connection to the API endpoint using the open() method. This method takes two arguments: the HTTP method (GET, POST, etc.) and the API endpoint URL.

       xhr.open('GET', 'https://api.example.com/data');
      
    3. Set request headers (optional) : If your API requires headers to be sent with the request, you can set them using the setRequestHeader() method.

       xhr.setRequestHeader('Authorization', 'Bearer TOKEN');
      
    4. Send the request : After setting any necessary headers, you can send the request to the server using the send() method. This method takes an optional argument, which can be used to send data with the request for methods like POST or PUT.

       xhr.send();
      
    5. Handle the response: Finally, you need to handle the response from the server using the onload() event listener. This event is triggered when the server responds with a status code in the 200 range. Inside the event listener, you can access the response data using the responseText property of the XHR object.

       xhr.onload = function() {
         if (xhr.status === 200) {
           console.log(xhr.responseText);
         } else {
           console.log('Request failed. Returned status of ' + xhr.status);
         }
       };
      

To sum up, here is the code for the overall implementation of the steps discussed above:

    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.example.com/data');
    xhr.setRequestHeader('Authorization', 'Bearer TOKEN');
    xhr.onload = function() {
      if (xhr.status === 200) {
        console.log(xhr.responseText);
      } else {
        console.log('Request failed. Returned status of ' + xhr.status);
      }
    };
    xhr.send();

Here, we're making a GET request to 'api.example.com/data'. When the server responds with a status code in the 200 range, we're logging the response text to the console, else we are logging the error message with the status code.

  1. Fetch API:

    Fetch API is a modern API for making HTTP requests. It is a Promise-based API, which makes it easier to handle responses than the XHR object. It is supported in all modern browsers and is mostly used method for making API calls in Javascript. The major steps involved are :

    1. Make a request : Use the fetch() method to make a request to the API endpoint. The fetch() method returns a Promise, which can be used to handle the response from the server.

       fetch('https://api.example.com/data')
      
    2. Handle the response: Use the then() method to handle the response from the server. The then() method takes a callback function as an argument, which is executed when the Promise is resolved.

       fetch('https://api.example.com/data')
         .then(response => {
           // handle the response
         })
      
    3. Extract the data: Use the json() method to extract the response data from the response object. This method returns another Promise, which can be used to handle the JSON data returned by the API.

       fetch('https://api.example.com/data')
         .then(response => response.json())
         .then(data => {
           // handle the JSON data
         })
      
    4. Error handling: Handle any errors that occur during the API call using the catch() method.

       fetch('https://api.example.com/data')
         .then(response => response.json())
         .then(data => {
           // handle the JSON data
         })
         .catch(error => {
           console.log(error);
         })
      

To sum up, here is the code for the overall implementation of the steps discussed above:

    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => {
        console.log(data);
      })
      .catch(error => {
        console.log(error);
      });

In this example, we're making a GET request to the API endpoint 'api.example.com/data'.When the server responds, we're extracting the JSON data using the json() method and logging it to the console. If an error occurs during the API call, we're logging the error to the console.

Those were the two mostly used methods of making API calls in Javascript. There are other methods as well such as :

i. Axios: Axios is a popular third-party library for making HTTP requests in JavaScript. It provides a simple and consistent API for making requests, handling errors, and working with responses.

ii. jQuery AJAX: jQuery is a popular JavaScript library that provides a simplified way to make HTTP requests using its AJAX API. It supports all HTTP request methods and provides a wide range of options for customization.

In conclusion, making API calls in JavaScript is an essential skill for any web developer. The two most popular ways of making API calls are using the Fetch API and XHR object.

Both Fetch API and XHR object have their own advantages and disadvantages, and the choice of which to use depends on the specific requirements of your application.

With the Fetch API, you have a more modern and easy-to-use interface, with support for Promises and the ability to handle responses in multiple formats.

On the other hand, the XHR object provides more fine-grained control over the request and response, with support for features like progress tracking and request cancellation.

Regardless of which approach you choose, it's important to handle any errors that may occur during the API call and to follow best practices for security and performance.

By mastering the art of making API calls in JavaScript, you can unlock a world of possibilities for your web applications, from integrating with third-party services to building custom backends for your own APIs.