Making API calls in JavaScript

Making API calls in JavaScript

Often, when building an application it need to communicate with external resources. This is usually achieved using Application Programming Interfaces (API). JavaScript provides a number of ways to perform API calls. I'm gonna discuss four methods in this article. The first two, XMLHttpRequest and fetch, are in-built and supported by the browser. Axios and JQuery are third party libraries that need to be loaded via a CDN. I prefer writing my API calls in functions for easier reusability throughout an application.

XMLHttpRequest

XMLHttpRequest is a legacy method built into the browser. It returns the data in text format by default and the data needs to be converted to JSON format. This method is rarely used nowadays but other external libraries are built on top of it. The code is shown below

// using the built in XMLHttpRequest method to make an api call
let url = "https://dog.ceo/api/breeds/image/random"
const get_data = (url) => {
    const req = new XMLHttpRequest;
    req.open("GET", url);
    req.send();
    req.onload = () => {
    if (req.status === 200) {
        data = JSON.parse(req.responseText);
        console.log(data)
        } else {
        console.log(req.status);
    }
  };
};

get_data(url)
fetch

It is an in built method that is supported by most modern browsers. It works in a similar manner to XMLHttpRequest but uses promises. This method can be used either using the .then() method or using the async/await functions. The main drawback of fetch is poor error handling The code is shown below

// using the built in fetch method to make an api call

let url ="https://dog.ceo/api/breeds/image/random"
const get_data = async (url)=>{

    //try/catch block to handle errors
    try {
        res = await fetch(url);  //promise returned 
        data = await res.json(); //formating data in json
        console.log(data);
        return data;
        } catch (error) {
        console.log(error);
    }
}

get_data(url)
Axios

It is an open source third party http client based on promises and built on top of XMLHttpRequest. It provides great features for making API calls and supports a wide range of browsers. It can work in the browser, node.js environment or with libraries such as react. It also has great error handling. In order to use the library you need to load the CDN

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js" integrity="sha512-bZS47S7sPOxkjU/4Bt0zrhEtWx0y0CRkhEp8IckzK+ltifIIE9EMIMTuT/mEzoIMewUINruDBIR/jJnbguonqQ==" crossorigin="anonymous"></script>

The code is shown below

//using third party axios library 

let url ="https://dog.ceo/api/breeds/image/random"
const get_data = (url)=>{
    axios.get(url).
    then(response =>{
        data = response.data //rerurns data 
        console.log(data)
        return data;
    }, err=>{
        console.log(err) //handles errors
    })
}

get_data(url)

Axios is the most used library for making http requests.

JQuery
It is also an open source third party built on top of XMLHttpRequest. To use this library you need to load its CDN. Provides for great error handling and returns data in JSON format directly

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"></script>

The code is shown below

// using third party jquery library

let url ="https://dog.ceo/api/breeds/image/random"
const get_data = (url)=>{
    $(document).ready((url)=>{  //making request
        $.ajax({
            type: "GET",  //defining the method
            url : url,
            dataType: "json",
            success: (res)=>{
                console.log(res)
                return res;
            },
            error: (err)=>{  // error handling
                console.log(err)
            }
        })
    })
}

get_data(url)