In JavaScript, All Possible API Calls Are Listed

It was critical in JavaScript to understand how to make HTTP requests and obtain dynamic data from the server/database.

To interface with the APIs, JavaScript offers several built-in browser objects as well as some additional open source libraries.

Here are some methods for making an API call:

XMLHttpRequest

fetch

jQuery

XMLHttpRequest

Before ES 6 comes out, the only way to make an HTTP request in JavaScript was XMLHttpRequest. It is a built-in browser object that allows us to make HTTP requests in JavaScript.

JSONPlaceholder is a free online REST API that you can use whenever you need some fake data.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

XMLHttpRequest
Prior to the release of ES 6, the only option to make an HTTP request with JavaScript was to use XMLHttpRequest. It’s a browser object that lets us make HTTP requests in JavaScript.

JSONPlaceholder is a free online REST API that you may use whenever you need to generate fictitious data.

Fetch

Fetch Fetch allows you to make an HTTP request in the same way as XMLHttpRequest does, but with a more user-friendly interface based on promises. It is not supported by older browsers (but can be polyfilled), however it is extremely well supported by newer browsers. We can use fetch to perform an API call in two ways.

The Fetch API provides a JavaScript interface for interacting with and altering protocol elements such as requests and answers. It also has a global fetch() function for retrieving resources asynchronously via the network in an easy and logical manner.

Previously, XMLHttpRequest was used to provide this type of functionality. Fetch is a superior option that other technologies, such as Service Workers, can simply utilise. Fetch also provides a reasonable location to specify additional HTTP-related notions like CORS and HTTP extensions.

// Example POST method implementation:
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData('https://example.com/answer', { answer: 42 })
  .then((data) => {
    console.log(data); // JSON data parsed by `data.json()` call
  });

In this case, we’re retrieving a JSON file from the network and writing it to the terminal. The most basic usage of fetch() takes one input — the path to the resource to be fetched — and instead of immediately returning the JSON response body, produces a promise that resolves with a Response object.

The Response object, on the other hand, is a representation of the whole HTTP response and does not directly include the actual JSON response content. So, we utilise the json() function to extract the JSON body content from the Response object, which returns a second promise that resolves with the result of parsing the response body text as JSON.

jQuery

There are several techniques in jQuery for dealing with asynchronous HTTP requests. To utilise jQuery, we must include the jQuery source file, and the $.ajax() function is used to make the HTTP call.

$( document ).ready(function() {
  let endpoint = 'https://api.linkpreview.net'
  let apiKey = '5b578yg9yvi8sogirbvegoiufg9v9g579gviuiub8'

  $( ".content a" ).each(function( index, element ) {

    $.ajax({
        url: endpoint + "?key=" + apiKey + " &q=" + $( this ).text(),
        contentType: "application/json",
        dataType: 'json',
        success: function(result){
            console.log(result);
        }
    })
  });
});

This is how Ajax requests are structured: the contents of $.ajax() are essentially an object that accepts values to be used in the construction of the request. The above example is as as basic as it gets for performing a GET call. We’re looping through each tag and sending its contents (the url) to the API, which returns an object.

Ajax requests can accept even more parameters than the ones we’ve just listed. I recommend carefully reading the JQuery Ajax documentation; not just for the sake of these requests, but also for understanding the various elements we might specify, which will strengthen our grasp of REST APIs in general.

The line contentType: “application/json” specifies that the content coming back to us will be in JSON format – this is a very common header when dealing with REST APIs.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories