Before we talk about APIs in JavaScript and how to use them, we need to know what exactly we mean by APIs. API stands for Application Programming Interface and is a concept that is not limited or specific to JavaScript, but is used in almost all web application languages. Being a web developer, it is expected that you know about API, so let’s try to understand the concept first. 

As a concept, API has been there since more than 50 years, but in recent years it has become very popular and has outlined a different method for how we create our applications. Now imagine you are creating a web application where users can sign up and talk about their recent travels, write stories, post pictures and share them. As an add-on they should be able to share the same across multiple platforms like Facebook, Instagram etc. How do we do that? We don’t have access to the Instagram application or their data. We don’t know how they are managing their data and whether data from our application will fit into their databases.  

Let’s try to imagine how Instagram would allow add-on without APIs. Perhaps we might drop an email to Instagram asking them to allow us access to their databases where we can write content. They may have received millions of other such requests from people who also need to use Instagram add-ons. Instagram will go through our requests and the million others and probably would use a lucky draw to decide who gets access to their databases. This is obviously not a reasonable solution and without any reasonable solution all applications in the world will just become isolated; which means they can’t communicate and can’t support each other’s features. Luckily our imagination is just that!

Fortunately, we are living in a world with APIs around us which allow us to easily communicate with other apps. I can create an application where I can use Google’s search, Facebook’s feed, Instagram’s post, twitter’s tweets all in one app. This is all possible using API. As the name suggests, it allows us to open an interface which can then be used by other apps to communicate using the interface. 

How does an API work?

The purpose of API is to communicate between apps with each other as intermediary, where both apps might have been built with different tools and technologies. It can be achieved by using api standards like REST, SOAP which outline protocols or sets of rules which the client (who needs to call) and server (who serves client’s requests) need to follow. These standards are key to communication. These standards outline what a request should look like and the format in which client should expect response from server. 

Every api exposes its endpoints (also called entrypoints), which allows its client to use it to access features of apis. For example, in JavaScript, to work with DOM, it exposes Document as an entrypoint in order to work with multiple methods. It allows its client to use it in order to manipulate DOM. In JavaScript however we use containers, which are nothing but HTML controls which can call APIs and response can be rendered within that control. 

JavaScript: An Introduction 

JavaScript is one of the most widely used programming languages, even though it is mainly used on browsers to render HTML and CSS. It can also run on our servers to handle client requests, connect with databases and do almost everything any other programming language does on the server. This makes it a significant tool that needs to be learned. 

Here, we are going to discuss about APIs which are provided by JavaScript to work with almost every aspect of a web application. 

APIs in JavaScript 

JavaScript, being a very widely used programming language has a very large set of APIs available, which make a JavaScript developer’s life a lot easier. JavaScript is also a multi-purpose language which means it can not only work on browsers, but also on servers or phones. To support different platforms, it has a different set of APIs to work with. It also provides a rich set of controls and other features like storage on client which are all easily availed by JavaScript.  

Browser APIs in JavaScript 

Browsers use JavaScript to display web pages, handle user interactions, send requests to servers and to receive responses. To make all this possible, JavaScript provides browser APIs which can be used to perform browser related functions:  

  1. Working with DOM  

DOM stands for Document Object Model, which is a structure that holds all HTML controls on a web page. It not only holds but also allows us to add remove controls from it. You might have worked with document API which is used to get, push or even remove elements from DOM, all of this is coming from JavaScript DOM API. 

Example: document.getElementById(“header”).text(“This is a header”); 

  1. Request data from server 

JavaScript is widely used to optimize web pages by updating only a part of a webpage instead of loading the entire page. for example, when you like a post on Facebook, it doesn’t load the entire page again, it only updates that particular post. Similarly, when we tweet on Twitter it doesn’t reload the entire page to show new tweets. This is how JavaScript makes partial calls to the server using popular fetch, AJAX apis. 

Example: 

const response= await fetch(url); 
// when response is success which is status 200 
if (response.ok) {   
  // receive response from server. 
  let json = await response.json(); 
} else { 
  // if there are errors returned by server, show the error 
  alert("Error occured" + response.status); 
}
  1. Store data at client 

Even though we have our databases working smoothly on servers processing terabytes of data every day, you might still want to store a chunk of data on the client’s browsers to optimize the application performances. How do we do that? 

Again JavaScript will show us the way, by providing APIs like localStorage, sessionStorage which we can use to store data on client’s browser and remove it whenever we want. The difference between localStorage and sessionStorgae is that data which we store in localStorage persists even after closing the browser or tab,  whereas data stored in sessionStorage gets cleared as soon as the tab or browser is closed. Now both of these have its own advantages depending on your requirement.

sessionStorage.setItem('key', value); 
sessionStorage.getItem('key')  
localStorage.setItem('key', value); 
sessionStorage.getItem('key';)
  1. Work with Graphics 

There are lot of popular applications where you might have seen  2D or 3D graphics created using user’s interaction allowing users to create such drawings, and I am not talking about just CSS (Cascaded Style Sheets). Yes, CSS has its role to play, but to allow users to create 2D/3D drawings on the web we need more than just CSS. JavaScript provides canvas api which can be used to work with pixels on web page to draw 2D/ 3D images which will be within <canvas> html tag.

Third Party APIs.  

Integration with other applications, the structures of which we don’t have much information about, can be difficult. But JavaScript allows us to integrate with many popular third-party apps like Twitter, YouTube, Facebook. 

For example, you have your company’s website where you also want to display recent tweets that your company’s Twitter account has tweeted. How do we do that? JavaScript’s Twitter API is the answer. This is not only for Twitter, but a lot of other popular apps can be integrated into your own web page using JavaScript’s third party APIs. 

Web Audio API  

Audio API in JavaScript provides a smooth implementation of audio controls over a webpage. This includes multiple play controls on audio, and audio effects on the web. Web Audio API has multiple interfaces which include operations related to visualization effects, audio destinations, merging audio channels and audio processing. 

Example 

<div> 
  <audio src="https://www.knowledgehut.com/blog/web-development/myfavsong.mp3"></audio> 
  <button>Play</button> 
  <input type="range" min="0" max="1" step="0.01" value="1"> 
</div>

Geolocation API

There are many web apps which work best with information of user’s locations, for example, if you are looking for restaurants nearby, you will get better results if Google knows your location. It is obviously up to the user’s consent if they want to share their location or not due to privacy concerns, but if they do want to share, geolocation API provides location of users to web applications. 

Example: 

var address = document.getElementById("address"); 
function accessUserLocation() { 
  if (navigator.geolocation) { 
navigator.geolocation.getCurrentPosition(displayLocation); 
} 
} 
function displayLocation(location) { 
address.innerHTML = "Latitude: " + location.coords.latitude +   
"Longitude: " + location.coords.longitude;   
}

History API  

History API is another useful although rarely used API, used if you want to allow user to traverse back and forth on a web application. History API runs with window objects using three different methods available– go, back and forward. 

Example: 

// Visit page visited previously 
window.history.back(); 
// Traverse to forward on web page. 
window.history.forward(); 
// Move forward by 1 page 
window.history.go(1); 

Web Workers API  

Workers can be created using constructors in JavaScript, which can run a JavaScript file under worker thread context, which is different from the context of windows in JavaScript. There are a few exceptions on what kind of code we can run under worker thread, for example we can’t manipulate DOM using worker thread. With this a question arises– if worker thread is different form main window thread, then how do they communicate? Because even though it is running in a different thread, the worker can still execute many window methods. To make this possible, the worker and main thread communicate using postMessage() method; to send data whenever onmessage event is called and handled. 

Example: 

const worker = new Worker('input.js'); 

Here input file which is a JavaScript file will contain the code which you need the worker thread to execute. 

Most Popular JavaScript APIs 

  • Browser APIs  We have discussed them in detail and since JavaScript leads how web applications are rendered on browser, the popularity of browser APIs is obvious. 
  • Canvas APIs  This is another favorite API of many developers who work in the graphics domain and need interactive applications for their client to easily work with drawings and graphics on web pages. 
  • SocialMedia APIs – This is very common nowadays. Any web application that targets an audience, needs social media integrations in their app, such as Facebook, Twitter, Instagram APIs, where they can showcase recent activities on their web page. 
  • Storage APIs  Every site I browse now a days pops up a panel asking me to accept cookies settings. Why? Because it helps the applications work well with user’s interaction and responses to the app, and the storage is not limited to cookies. sessionStorage and localStorage are widely used in JavaScript applications to store user’s info on client’s browsers. We just can’t imagine a life without storage APIs in JavaScript! 

JavaScript tools and relationship between them

JavaScript Libraries

 There are JavaScript libraries like jQuery and React which implement JavaScript with their own new syntax. For example, the way we access our DOM using vanilla JavaScript and the way jQuery does it is different, but in the end, both use the same API which we have discussed above. Another example is when using React, where it extends JavaScript with JSX to embed JavaScript with HTML in React components.

JavaScript Frameworks

JavaScript Frameworks like Angular and Vue make most of the JavaScript APIs as they are built on top of JavaScript. The difference between the frameworks is in the structure, data flow and different patterns which they use to make it easier to work with JavaScript and implement its APIs.  

For example, Angular uses Dependency Injection to inject services into the component’s constructors, making it a sophisticated form of implementing inversion control which would be not this smooth with vanilla JavaScript. Frameworks like Angular try to prevent users from manipulating DOM directly as it is an expensive operation. However, it doesn’t mean it doesn’t update DOM at all. In the end, Angular uses DOM manipulation internally in quite an effective way, using the same APIs we have discussed above.

Conclusion 

An API can be compared to a phone with unlimited talk time that is given to an application, allowing it to communicate with all other applications in the world. Why do we need this? Because one application doesn’t need to and can’t do everything. They need each other’s help. 

APIs can be for external as well internal use. External APIs allows an app to communicate with other apps, and internal or built-in APIs allow developers to work effectively with the tools. JavaScript being the most popular language in the world is aware of this and hence presents plenty of interfaces for us as developers to use in our applications. Be it working with storage, creating controls, integrating with Twitter, presenting media, or drawing graphics, JavaScript will not let you down.