How to call an API using vanilla Javascript

Bhuman Soni
Bhuman Soni August 7, 2022
Updated 2022/08/09 at 1:57 PM

This post looks at how you can call an API using vanilla Javascript using code samples to explain concepts. These days you will spend a majority of your time working with a framework like Angular, ReactJS, VueJS etc and to call an API with that would be quite easy and straightforward. However it is always good to know the basics.

Why should you know the basics?

Knowing how to work with frameworks will make you a good engineer/developer and an expert in the framework. However, knowing the basics of how things work and make you a great engineer/developer. Also, you may not always be using the same framework in your job or your personal project so knowing the basics can only help you learn new frameworks faster.

Call an API using vanilla Javascript – Using XMLHttpRequest

Originally developed by the team working on Outlook web access for Microsoft Exchange Server 2000, it gained popularity with the Web 2.0. Supported by almost every browser out there. The XMLHttpRequest object is one of the most basic means for client-side Javascript to communicate with a server.

What is it?

As you know Javascript is object oriented and XMLHttpRequest is an object that is used to communicate with servers. In better words, it facilitates two way communication between client-side Javascript and web servers. It was build with the intent of modifying a web page after it was loaded by fetching data from the servers.

How execute a GET request?

You can get a feel of how this method works by calling a simple get request from the server. You can try to GET some data by invoking this url (https://httpbin.org/cookies). Your code will look like the following,

  function queryAPI() {
    function reqListener() {
      console.log("Response received");
      console.log(this.responseText);
    }

    const oReq = new XMLHttpRequest();
    oReq.addEventListener("load", reqListener);
    oReq.open("GET", "https://httpbin.org/cookies");
    oReq.send();
  }

Alternatively another way to check for a response is by tracking the onreadystatechange method. You can do that as follows.

  function queryAPI() {
    const oReq = new XMLHttpRequest();
    oReq.open("GET", "https://httpbin.org/cookies");
    oReq.send();
    oReq.onreadystatechange = function () {
      console.log("ready state changed");
      console.log(this.responseText);
    };
  }

Summary of GET calls

As you saw in the above method, they both work by

  1. Creating an object of XMLHttpRequest
  2. Creating a request by opening a connection to a url by specifying the http method (GET) and url
  3. Sending the request to the server
    1. Then The first method attaches a method reqListener that checks for the load event for response
    2. The second method attaches a function to the onreadstatechange event for response
  4. Both methods print out the responseText once the response is received

How to execute a POST request?

Executing a post request is not too hard either, it is actually quite simple. Have a look at the code below

  function postToAPI() {
    const url = "https://httpbin.org/post";
    const oReq = new XMLHttpRequest();
    oReq.open("POST", url, true);
    oReq.onreadystatechange = function () {
      console.log("ready state changed");
      console.log(this.responseText);
    };
    const postData = {
      greeting: "hello world"
    };
    oReq.send(postData);
  }

Again, for the purpose of this tutorial you can make use of the httpin.org/post method. https://httpbin.org is a handy little site, take a look at it at your leisure and see all the cool stuff it has. As you can see it is very similar to the GET call except,

  1. When you create a request, you specify the http method as “POST” and
  2. When you call the oReq.send method, you pass in some data

Can we use arrow functions?

All of the above code is fine and it works, you can re-write it using modern Javascript e.g. you can use arrow functions. To re-write the above functions using arrow functions, the code would look something like,

XMLHttpRequest for GET call

  const queryAPI = () => {
    const oReq = new XMLHttpRequest();
    // oReq.addEventListener("load", reqListener);
    oReq.open("GET", "https://httpbin.org/cookies");
    oReq.send();

    oReq.onreadystatechange = () => {
      console.log("ready state changed");
      console.log(oReq.responseText);
    };
  };

Remember, you will loose the “this” reference when you are working with Arrow functions. Hence remember to use theXMLHttpRequest object which in this case is oReq in the subsequent function calls.

XMLHttpRequest for POST call

  const postToAPI = () => {
    const url = "https://httpbin.org/post";
    const oReq = new XMLHttpRequest();
    oReq.open("POST", url, true);
    oReq.onreadystatechange = () => {
      console.log("POST Req ready state changed");
      console.log(oReq.status);
    };
    const postData = {
      greeting: "hello world"
    };
    oReq.send(postData);
  };

call an API using vanilla Javascript – XMLHttpRequest Summary

After reading this post you should know how to execute a GET and POST request using XMLHttpRequest object from client-side Javascript. You can use the concepts here to trigget DELETE request from client-side Javascript.

Conclusion

Once again this post was a trip back in time and you learned the basics of browser based communication with the server. As of now, there is no reason for you to use XMLHttpRequest in your web app but it is still one of the most widely supported API for browsers. Knowing the basics is always beneficial.

Subscribe & never miss a post

If you find any of my posts useful and want to support me, you can buy me a coffee 🙂

https://www.buymeacoffee.com/bhumansoni

Alternatively you can have a read of one of my other posts on vanilla Javascript,

What is Javascript event loop? – My Day To-Do (mydaytodo.com)

How to build a game using Vanilla Javascript – My Day To-Do (mydaytodo.com)

Vanilla Javascript: Create Radio Buttons (How-To) – Bhuman Soni (mydaytodo.com)

Java Spring Boot & Vanilla Javascript solution – My Day To-Do (mydaytodo.com)

Vanilla Javascript: Create Radio Buttons (How-To) – Bhuman Soni (mydaytodo.com)

While you are here, maybe try one of my apps for the iPhone.

New tab (mydaytodo.com)

Apps – My Day To-Do (mydaytodo.com)

Share this Article
Leave a comment

Leave a Reply

Your email address will not be published.

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock