Web APIs for Advanced Web Development
Web APIs, also known as browser APIs, can enhance a browser’s functionality. They are built into the browser using JavaScript, allowing you to quickly implement complex functionalities.
Web APIs are very useful in web development as they let developers carry out complicated actions by exposing data from the browser.
The web browser provides different APIs that can enhance the functionalities of apps. Some of these include APIs for data fetching, APIs for drawing and manipulating graphics, and APIs for storing data on the browser.
In this article, I’ll be working with the following web APIs to understand how they function and also how to implement them in projects.
1. Fetch API
The Fetch API provides a JavaScript interface that is built into most modern browsers and it is used to make HTTP requests to web servers.
There are two ways of requesting data using the Fetch API: You can either use promises or async/await, which was introduced in ES6.
Let’s take a look at how to fetch data using both methods.
Using Async/Await
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Document</title>
</head>
<body>
<div class="container">
<h2>Advice Generator</h2>
<p id="content"></p>
<button type="submit" id="submit">generate advice</button>
</div>
<script src="index.js"></script>
</body>
</html>
CSS
body {
font-family: sans-serif;
}
.container {
width: 30rem;
background-color: rgb(3, 3, 12);
text-align: center;
padding: .5rem 0rem 2rem 0rem ;
margin: auto;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: rgb(25, 194, 61);
}
#content{
padding: .5rem 2rem;
color: #fff;
}
button{
padding: .5rem 1.5rem;
border: 1px solid #19c23d;
border-radius: 5px;
background-color: #000;
color: #fff;
font-size: 20px;
}
JavaScript
const result = document.getElementById("content");
const submitBtn = document.getElementById("submit");
let myAsyncFunction = async () => {
let response = await fetch("https://api.adviceslip.com/advice");
let data = await response.json();
result.textContent = data.slip.advice
return data;
};
submitBtn.addEventListener("click", myAsyncFunction)
- A constant result is defined and assigned to the element with the ID “content”
- A constant submitBtn is defined and assigned to the element with the ID “submit”
- An async function
myAsyncFunction
is defined - The
myAsyncFunction
makes a request to the “https://api.adviceslip.com/advice” API and waits for a response - The response is converted to JSON format and the advice is added to the text content of the result element
- The
myAsyncFunction
is added as an event listener for the “click” event on the submitBtn element - When the submitBtn is clicked, the
myAsyncFunction
is called and the advice is fetched and displayed on the page.
Using Promises
const result = document.getElementById("content");
const submitBtn = document.getElementById("submit");
const API = "https://api.adviceslip.com/advice";
function generateAdvice() {
fetch(API)
.then((response) => response.json())
.then((data) => {
result.textContent = data.slip.advice
});
}
submitBtn.addEventListener("click", generateAdvice)
The process is quite similar to using async/await except in this case we are using promises to make the API call. That way, the logic happens inside callbacks that fire when the response is received. In the meantime, the program will continue beyond the fetch(API) line.
The output should look like the image below. See the demo here and check out the GitHub repository.
Browser Support
The Fetch API is supported by all browsers except Opera Mini and Internet Explorer.
2. File API
The File API enables web applications to access files and their contents. Web apps can access files when a user makes them available through drag and drop or using <input type=”file”>
. These files can be passed to the Filereader object to read and access the file’s content. Filereader is also built into the browser, meaning you do not have to install it as a dependency.
To work with the File API, we need to have a basic setup in our HTML, CSS, and JavaScript files.
HTML
<br />
<img data-id="preview" height="200" alt="Image preview" id="preview" />
In the HTML file, there’s an input element with a type of file and an accept attribute that allows users to select and filter file extensions from their device. Instead of listing out the extensions, you could also use “image/*” in accept to accept all image files. There’s also an image element to help display the files uploaded from our device and data attributes for JavaScript DOM targeting.
JavaScript
First, we define the variables for the input and image element:
const selectFile = document.getElementById("file");
const preview = document.getElementById("preview");
Next, we add an event listener to the input element — in this case, selectFile
— that takes in two parameters. This event listener detects a change in the input field. As soon as the change is fired, it will invoke the function that handles the process of our image upload.
We assign a variable, file
, to target the first element in our device. Next, we declare another variable, reader
, and assign it to the FileReader API. After that, we add another event listener to reader
that listens for a load event, which will invoke the function that allows us to preview the image that’s being uploaded from our device. Finally, reader
will read the content of the file we’re uploading using the readAsDataURL
.
selectFile.addEventListener("change", function () {
const file = selectFile.files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
});
if (file) {
reader.readAsDataURL(file);
}
});
CSS
body {
background-color: rgb(162, 162, 226);
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
img {
margin-top: 1.5rem;
}
The result should look like the image below. For more, check out the demo.
Browser Support
The File API is supported by all browsers except Opera Mini and Internet Explorer.
3. EyeDropper API
The EyeDropper API provides a technique for creating an eyedropper tool. This tool allows users to select colors from their screen and also access the hex value of the color selected. The <input type="color">
on the Chromium-based desktop browser is quite similar to this tool as it also allows users to sample colors from their screen.
The downside to using that element is that it will require a lot of customization to make it available to the other parts of the user’s screen whereas the eyedropper tool offers a simpler interface to pick a color from the entire device screen.
Sampling a color using the EyeDropper tool
HTML
First, we set up a basic HTML file that has a body tag, a button to hold the eyedropper tool, and a paragraph to display the hexcode of the color selected.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<button id="selectBtn">Open the colorpicker</button>
<p>The color code is : <br> <span id="result"></span></p>
<script src="/app.js"></script>
</body>
</html>
CSS
body{
display: flex;
justify-content: center;
margin: 10rem auto;
}
button{
background-color: #000000;
color: #fff;
border-radius: 10px;
border: 1px solid #ffc0cb;
margin-right: 1rem;
}
span {
font-weight: bold ;
}
JavaScript
const selectBtn = document.getElementById("selectBtn");
const hexcode = document.getElementById("result");
const bgColor = document.querySelector("body");
const eyeDropper = new EyeDropper();
selectBtn.addEventListener("click", () => {
eyeDropper.open()
.then((colorSelectResult) => {
hexcode.textContent = colorSelectResult.sRGBHex;
bgColor.style.background = colorSelectResult.sRGBHex;
})
.catch((err) => {
hexcode.textContent = err;
});
});
- First, declare the variables for the body element, button element, and span element.
- Next, create an EyeDropper object and assign it to the eyeDropper variable, which allows us to use the API.
- After that, add an event listener to the button element; this event is triggered when a user clicks on the button.
- Call the open() on the eyeDropper variable and this returns a promise that resolves to an object and gives access to the selected color in sRGBHex format.
- Finally, we want to manipulate the body of the app to take up the color that the eyedropper tool selects.
The output should look like the image below. For more, watch the demo and check out the GitHub repository.
Browser Support
The EyeDropper API is supported by the latest versions of the following browsers:
- Chrome
- Edge
- Opera
4. Web Speech API
The Web Speech API enables you to incorporate voice data into web apps, which makes it easy to add voice recognition to them. This API has two components:
Speech recognition
The speech recognition API is a part of the Web Speech API that allows authorized web applications to access a device’s microphone and produces a transcript of the voice being recorded.
Speech synthesis
The speech synthesis API, also known as text-to-speech, is a part of the Web Speech API that changes text content to voice content. It allows the browser to read out content from the screen using different voices and pitches.
This feature is really awesome and it can be integrated into blogs to aid accessibility for the visually impaired. Let’s take a look at how to integrate the text-to-speech feature into our app.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>text-to-speech</title>
</head>
<body>
<div>
<!-- <form> -->
<textarea name="text" id="text" cols="30" rows="10" placeholder="enter text"></textarea>
<select name="" id="select">
select voices
</select>
<button type="submit" id="submit">Speak</button>
<!-- testing -->
<!-- </form> -->
</div>
<script src="/app.js"></script>
</body>
</html>
CSS
body {
background-color: aquamarine;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
div {
display: flex;
flex-direction: column;
}
select{
margin: 2rem 0 2rem 0;
padding: .5rem 0 .5rem 0;
}
button{
padding: 1rem 0 1rem 0;
border: 2px solid green;
border-radius: 10px;
background-color: teal;
font-size: 1.5rem;
color: #d8bfd8;
font-family: monospace;
}
JavaScript
First, we target and assign variables to the textarea element, select element, and button element. We also want to check whether our browser supports the Web Speech API.
const text = document.getElementById("text");
const submitBtn = document.getElementById("submit");
const voiceSelect = document.getElementById("select");
if ("speechSynthesis" in window) {
console.log("Web speech API supported");
} else {
console.log("Web speech API not supported");
}
We then add an event listener that fires when the submitBtn
is clicked; this action grabs the content from our textarea. With that text, we’ll create a SpeechSynthesisUtterance
and then pass it to speechSynthesis.speak
.
submitBtn.addEventListener("click", () => {
let output = text.value;
const utterThis = new SpeechSynthesisUtterance(output);
speechSynthesis.speak(utterThis);
});
With this, the browser should be able to read out the content in the textarea. Let’s take it a step further by adding an extra feature that allows the browser to read out different voices based on selection.
Adding the voice selection feature
Let’s initialize two empty variables: voices
and currentVoice
. Once that’s done, we create a function that calls the getVoices()
method on speechSynthesis
and assigns it to the Voices variable
. Next, we loop through the voices we got from the getVoices()
method. We then create an option element, populate it with the voices, and append the option element to voiceSelect
.
We also listen for the onVoicesChanged
event and assign it to populateVoices
to repopulate a list of voices that the user can choose between when the event fires.
let voices = [];
let currentVoice;
const populateVoices = () => {
voices = speechSynthesis.getVoices();
voices.forEach((voice) => {
const option = document.createElement("option");
let optionText = `${voice.name} (${voice.lang})`;
if (voice.default) {
optionText += " [default]";
}
option.textContent = optionText;
option.value = voice.name;
voiceSelect.appendChild(option);
});
};
populateVoices();
if (speechSynthesis.onvoiceschanged !== undefined) {
speechSynthesis.onvoiceschanged = populateVoices;
}
We want to add an event listener for a “change” event on a voiceSelect
element. When the event is triggered, the selected voice is determined by getting the value property of the event target and then use that value to search for a corresponding voice in the voices array. Once the correct voice is found, it is assigned to the currentVoice
variable.
voiceSelect.addEventListener("change", (event) => {
const selectedVoice = event.target.value;
currentVoice = voices[selectedVoice];
});
Finally, we will add utterThis.voice = current voice
to our submitBtn
event, which allows us to use the voice feature we just created.
submitBtn.addEventListener("click", () => {
let output = text.value;
const utterThis = new SpeechSynthesisUtterance(output);
// add piece of code here
utterThis.voice = currentVoice;
synth.speak(utterThis);
});
The final output should look like the image below. For more, see the demo and head over to the GitHub repository to get the complete code.
Browser Support
The Text-Speech-API is supported by the latest versions of the following browsers:
- Chrome
- Edge
- Opera
- Safari
- Firefox
5. Notification API
The Notification API allows web pages to send push notifications to users. For this API to work, the user must first agree to accept notifications. This permission request only shows once as the browser will always remember the user’s choice.
The permission can be in the form of the following strings:
- granted: the user accepts having notifications displayed
- denied: the user rejects having notifications displayed
- default: the user neither accepts nor rejects having notifications displayed
When the user agrees to accept this permission, the browser can now send notifications using the Notification object. The Notification takes in two parameters: title, which defines the title for the notification, and option, which takes in different options of notifications you might want to use. This option includes body, icon, vibrate, dir, etc.
How the Notification API works
First, we declare a function and we want the function to request permission from the user if the user agrees, we want to create a new notification object with a title, body, and icon and assign it to notify. We also want to listen for a click event on the Notification, which will redirect the user to the Mattermost website.
Next, we want to add a setTimeout function to close the Notification after a period of time:
const requestPermission = () => {
Notification.requestPermission().then((permission) => {
if (permission) {
const notify = new Notification("Mattermost Community", {
body: "There's a new chat in the community channel",
icon: "/mattermost.png",
});
notify.addEventListener("click", () => {
window.open("https://mattermost.com/");
});
setTimeout(() => {
notify.close();
}, 10 * 1000);
} else {
null;
}
});
};
Finally, we want to check if the Notification API is present in our browser. If it is, we want to call the requestPermission
function else console.log(“not available”)
.
if ("Notification" in window) {
requestPermission();
} else {
console.log("not available");
}
The final output should look like the image below. For more, watch the demo and visit the GitHub repository to get the complete code.
Browser Support
The Notification API is supported by the latest versions of the following browsers:
- Chrome
- Edge
- Opera
- Safari
- Firefox
Conclusion
Web APIs are an important part of the modern web ecosystem as they allow different applications to communicate and exchange data with each other in standardized formats. By providing a collection of shared tools, web APIs enable a wide range of functionality and possibilities for web-based applications, such as providing access to data from external sources, integrating with other platforms and services, and allowing for the creation of rich, interactive user experiences.
The web browser provides different web APIs that can enhance web applications. Aside from the APIs listed in this article, there are several others you can check out, like the Web Storage API. While you’re at it, check out the API list on caniuse to see how browser support is shaping up over time for the web APIs currently available.
Do you like reading articles like these? Head over to the Mattermost Library to continue your learning.