Crowdbotics Logo

Customers arrow

Don’t take our word for it, see what our customers have to say.

About Us arrow

We are on a mission to radically transform the software development lifecycle.

Home Blog ...

Web Development

10 Little-Known (But Very Useful) Web APIs

There are a wide range of web APIs available across the major internet browsers. Here are a few helpful APIs that you might not have heard of.

6 October 2021

by Shanika Wickramasinghe

What is a web API?

API stands for Application Programming Interface. An API is a way of allowing your application or a program to interact with another program using a simple set of commands. It doesn’t matter whether these programs are running on the same computer or not. Companies use APIs to serve their services and tools to their customers. You may know that some companies package their APIs as products.

Companies provide these APIs to augment their popular services, directly solve programming problems, and to save time. Software developers often use APIs to perform complex tasks easily in programming. APIs make software developers’ lives easier by giving proper access to data and low-level information.

Web APIs are included with internet-based products to give you the ability to access functions, properties, and useful objects required for carrying out tasks, such as managing graphics, videos, audio, and other assets.

Some Commonly Used Web APIs

If you’re a programmer, you may be familiar with the most commonly used web APIs. Here is a list of them:

These APIs are more commonly used than other APIs because they are standardized well. That means the majority of  web browsers support these well-known web APIs.

Less Commonly Used Web APIs

As a software developer, you can find a huge number of web APIs available. So, sometimes it will be difficult for you to keep track of new APIs.

Below, you’ll find a list of little-known web APIs that are useful when developing a web application. Even though they’re not commonly used today, some of them may become important in the near future for apps that connect to sensors, handle payments, and more.

Let’s explore some of them.

1.  Payment Request API

Payment workflows on web applications and websites often seem to be different from one another. But the steps of the workflow should always be as follows:

1.      Confirming the credit/debit card

2.      Adding the billing and shipping address

3.      Selecting the payment method

4.      Confirming everything

5.      Accepting the terms and conditions

6.      Sending the final request form

The many different payment flows in production on the web can create confusion among users. Moreover, the requirement to implement a new payment flow every time can be a very time-consuming process for the software developer, because the developer needs to integrate different payment methods like credit card or PayPal, implement different forms, and make everything secure.

The W3C Web Payments Working Group has developed the Payment Request API to simplify the process for everyone. It provides several interfaces for a consistent user experience for both users and merchants regarding payments while standardizing and facilitating the process of creating payment workflows.

Let’s see some example code of using the Payment Request API.

let paymentMethod = [{
    // ‘shopping-card' are standard card payments - debit and credit cards
    supportingMethods: 'shopping-card'
  }];
  
  let info = {
    // If multiple items are bought, we can include each one
    showItems: [
          {
            label: ‘Products we need to buy',
            amount: {currency: 'USD', value: ‘499.99'}
          }
    ],
    total: {
          label: 'Total',
          amount: {currency: 'USD', value: ‘499.99'}
    }
  };
  
  let paymentRequest = new PaymentRequest(paymentMethod, info);

In the above example, the configuration is set for the PaymentRequest – the type of payment and the information to display about the purchase.

2.  Web Bluetooth API

A standard that is often used in the field of IoT is the Bluetooth protocol. For instance, it is used to connect a tablet or smartphone to various other devices such as health trackers, which are used to read certain sensor values. You may know that PhoneGap and its plugins make it possible for mobile web applications to connect via Bluetooth.

But you need to install an extra browser plugin to use Bluetooth inside a web application on a laptop or desktop computer.

The Web Bluetooth API by W3C Web Bluetooth Community Group is a standardized API for connecting to Bluetooth devices. It provides access to Bluetooth devices through the browser. So there is no need for any plugins.

A promise to a BluetoothDevice object with the specified options is returned by the Bluetooth interface of the Web Bluetooth API.

navigator.bluetooth.requestDevice({
    acceptAllDevices: true
 }).then(device => {            
    setDeviceName(device.name);
    setDeviceId(device.id)
    setDeviceConnected(device.connected);
 }).catch(err => {
    console.log(err);
    setError(true);
 })

Please note that the Web Bluetooth API works on Edge and Chrome browsers but is not supported by Safari and Firefox.

3.  Vibration API

Many modern mobile devices have vibration hardware. They cause the device to shake, allowing software code to give physical feedback to the user.

The Vibration API allows you to connect to the vibration hardware of the system and perform operations. It offers ways to start the device vibration instantly or for a duration and stop it.

So, if the vibration hardware exists, web apps get the ability to access it using the Vibration API. If the device doesn’t support the Vibration API, it does nothing.

Keep in mind, this API works best on tablets and mobile devices. Even if the browser supports it, the Vibration API may not do anything on desktops.

useEffect(() => {
    if (start) {
       // Starting 4 seconds vibration
       navigator.vibrate(4000);
    } else {
       // stopping vibration
       navigator.vibrate(0);
    }
 }, [start]);

The Vibration API works only on the Chrome browser.

4.  Network Information API

You can use the Network Information API to get the details about bandwidth, save data mode, general network connection types like cellular or wi-fi, and other information. Based on the user’s connection, you can use the Network Information API to select low-definition content or high-definition content.

The entire Network Information API consists of a single property to the Navigator interface: Navigator.connection and the NetworkInformation interface.

console.log(navigator.connection);

Please note that the Network Information API works on Edge and Chrome browsers but is not supported by Safari and Firefox.

try our app estimate calculator CTA image

5.  Battery Status API

The Battery Status API or Battery API provides you the information about the battery of your devices, including PCs and laptops. So you can use it to know information such as the system’s battery charge level, the charge-related state changes, how much charge percentage is left, and whether the battery is charging or not.

The Battery Status API also allows you to receive notifications of certain events, such as when the charging status or battery level are changed. You can use the Battery Status API to prevent data loss by saving changes before the battery runs out. Besides, it also helps to reduce battery drain when the battery is low.

Please note that the Battery Status API is only supported on the Chrome browser.

You can use the following code to work with the battery-related details and to handle various events.

navigator.getBattery().then(function (battery) {
 
    // handling the charging change event
    battery.addEventListener("chargingchange", function () {
       console.log("Is Battery charging? " + (battery.charging ? "Yes" : "No"));
    });
 
    // handling the charge level change
    battery.addEventListener("levelchange", function () {
       console.log("The level of the Battery: " + battery.level * 100 + "%");
    });
 
    // handling the charging time change
    battery.addEventListener("chargingtimechange", function () {
       console.log( "The charging time of the battery: " + battery.chargingTime + " seconds");
    });
 
    // handling the discharging time change
    battery.addEventListener("dischargingtimechange", function () {
       console.log("The discharging time of the battery: " + battery.dischargingTime + " seconds");
    });
 
 });

6.  Performance Interface API

You can use the Performance interface to get access to performance-related information for the current page. It gives access to three major APIs: Timing, Memory, and Navigation.

Although the Performance Interface API is part of the High Resolution Time API, it is enhanced by the Resource Timing API, the User Timing API, the Navigation Timing API, and the Performance Timeline API.

If you want to obtain an object of this type, you have to call the window.performance read-only attribute.

The code for memory usage is as follows:

console.log(performance.memory);

The Performance Interface API works only on Chrome.

7.  Broadcast Channel API

You can use the Broadcast Channel API for communication between workers with the same origin and browsing contexts, such as iframes or frames, tabs, and windows.

You have to create a BroadcastChannel object to receive any posted messages to it. There is no need to continue a reference to the workers or frames that you want to connect with. Instead, they can construct their own BroadcastChannel with the same name to “subscribe” to a particular channel. Then they can communicate bi-directionally between all of them.

For instance, the following code shows how to use the Broadcast Channel API in a local HTML file.

<!DOCTYPE html>
 
<body>
  <!-- Changing the title to greet the user -->
  <h1 id="greeting">Hello</h1>
  <input id="name" placeholder="Enter Your Name"/>
</body>
 
<script>
 
let bCastChannel = new BroadcastChannel('example_channel');
 
(()=>{
  const greeting = document.getElementById('greeting');
  const name = document.getElementById('name');
  const setGreeting = (userName) => {
    greeting.innerHTML = 'Hello ' + userName;
  }
 
  bCastChannel.onmessage = (messageEvent) => {
    // If our broadcast message is 'update_greeting' then get the new greeting from localStorage
    if (messageEvent.data === 'update_greeting') {
      // localStorage is domain specific. That means if it changes in one window it changes in the other
      setTitle(localStorage.getItem('greeting'));
    }
  }
 
  // When the page loads checking if the greeting is in our localStorage
  if (localStorage.getItem('greeting')) {
    setGreeting(localStorage.getItem('greeting'));
  } else {
    setGreeting('What is your name?');
  }
 
  name.onchange = (e) => {
    const inputValue = e.target.value;
    // In the localStorage greeting is set to the user's input
    localStorage.setItem('greeting', inputValue);
    // Updating the greeting on the current page
    setGreeting(inputValue);
    // Telling the other pages to update the greeting
    bCastChannel.postMessage('update_greeting');
  }
})()
</script>

Internet Explorer and Safari browsers don’t have any support for Broadcast Channel API yet.

8.  Resize Observer API

The Resize Observer API is an effective mechanism that you can use in the code to monitor an element for changes to its size based on the changes to the border box of a DOM element or the content. The Resize Observer API also delivers notifications to the observer every time the size changes.

Now let’s consider how to use the Resize Observer API. To use the Resize Observer, you have to instantiate a new ResizeObserver object and pass in a callback function. This callback function receives the entries that are observed:

const observer = new ResizeObserver(entries => {
  // iterating over the entries, do something.
});

Then, observe can be called on our instance and an element can be passed in to observe:

const someElement = document.querySelector('.some-element');
const someOtherElement = document.querySelector('.some-other-element');
 
observer.observe(someElment);
observer.observe(someOtherElement);

The Resize Observer API works in Chrome and Firefox browsers.

9.  CSS Font Loading API

You know that it is time consuming to download the font files if you want to use custom fonts on a webpage. This process depends on the size of the font files and the bandwidth. Sometimes this may lead to display problems after loading. For instance, you may notice the content flickering when the webpage starts rendering without the font face being loaded first.

Now you have a solution to this problem. You can use the new Font Loading API to resolve this issue. It acts as a standardized API to download font faces by utilizing JavaScript. As a programmer, you can choose what to do when a font face has been downloaded and when to load it.

Here is an example of how to use CSS Font Loading API’s FontFaceSet.

// CSS 
.oxygen {
    font-family: Oxygen;
  }
.bitter {
    font-family: Bitter;
  }
 
// JavaScript 
const logLoaded = (fontFace) => {
    ChromeSamples.log(fontFace.family, 'loaded successfully.');
  }
  
 
  let fontFaceOxygen = new FontFace('Oxygen', 'url(https://fonts.gstatic.com/s/oxygen/v5/qBSyz106i5ud7wkBU-FrPevvDin1pK8aKteLpeZ5c0A.woff2)');
  document.fonts.add(fontFaceOxygen);
  fontFaceOxygen.loaded.then(logLoaded);
  let fontFaceBitter = new FontFace('Bitter', 'url(https://fonts.gstatic.com/s/bitter/v7/HEpP8tJXlWaYHimsnXgfCOvvDin1pK8aKteLpeZ5c0A.woff2)');
  document.fonts.add(fontFaceBitter);
  fontFaceBitter.loaded.then(logLoaded);
  
  document.fonts.ready.then(function() {
    ChromeSamples.log('There are', document.fonts.size, 'FontFaces are loaded.n');
 
    for (let fontFace of document.fonts.values()) {
      ChromeSamples.log('FontFace:');
      for (var property in fontFace) {
        ChromeSamples.log('  ' + property + ': ' + fontFace[property]);
      }
      ChromeSamples.log('n');
    }
  });

10.   FlyWeb API

Because of the rise of the Internet of Things, the ways that electronics and devices can interact and connect with each other have become more and more important. The FlyWeb API developed by the Mozilla team can be used to serve web applications on electronics and to connect to these applications from other electronics (for instance, with smartphones) within the same network.

For instance, when you connect a smartphone to a game console, the game console provides a small FlyWeb server that will be visible to the smartphone.

Let’s see an example of how the FlyWeb API is used to create a server from a web page. You can see it responds with a simple “Welcome to FlyWeb” HTML document.

navigator
  .publishServer('Welcome to FlyWeb')
  .then(function(server) {
    server.onfetch = function(event) {
      var html = `
        <h1>You are Welcome to FlyWeb!</h1>
        <h4>You requested: ${ event.request.url }</h4>
      `;
      let alternatives = {
        headers: { 'Content-Type': 'text/html' }
      };
      event.respondWith(new Response(html, alternatives));
    };
  })
  .catch(function(error) {
    console.log('publishServer() is failed :-(', error);
  });

Conclusion

You can use these web APIs to supercharge your programming skills. By automating repetitive tasks and eliminating common problems, you will be free to focus on other parts of your job.

Crowdbotics utilizes web APIs in the custom app builds using React Native and Django. Our expert PMs and devs are pros when it comes to integrating valuable APIs into your app. To see what’s possible, get in touch for a comprehensive estimate today.