Web APIs
Intro
- This tutorial covers JavaScript Web APIs.
- It is recommended that you follow along with each section below. Create a folder called webapis. Paste or type the code into your own JavaScript and HTML files.
- The example code for the entire tutorial series is at github.com/LearnByCheating/javascript-tutorial. There is a separate folder called webapis that holds the files from this tutorial. The Readme file has instructions on how to run the code in the Browser environment.
Web API Overview
- API stands for Application Programming Interface.
- It is an interface for a program to interact with a separate software component or resource. The API can provide data, functions, routines or other services to your program.
- JavaScript Web APIs are provided by web browsers but are not part of the JavaScript engine. They are also not part of the ECMAScript standards, and are not available in Node.js, although Node does have its own version of the console and timer APIs.
- Like the built-in JavaScript global objects such as String, Number, Date, Boolean, Object, Array, etc., Web APIs are attached to the window global object.
- Open the Dev Tools console on any web page and enter window, and you will see all the Web APIs along with the core JavaScript global objects.
- In this tutorial we will be looking at console, location, history, web storage, timers, and fetch. A separate tutorial will look at the DOM APIs for manipulating HTML documents. But be aware there are many more.
1. Console
- The console API has methods for logging messages to the console. They are particularly useful for debugging.
- You simply pass in a message as the argument and it will log it to the console.
console.log('This is a message.');
- Both the Web API and Node.js have console.log methods.
- On the web, console logs are printed in the web page's Dev Tools console.
- In Node.js, console logs are printed in the Terminal.
- VS Code has a Debug console that displays console logs when running your code with the Debugger.
- Console.log does not return a result, so the result is undefined. Logging the passed in message to the console is a function side effect.
const res = console.log('This is a message'); // logs "This is a message"
res; // returns undefined
- You can have multiple arguments in the method separated by commas. For instance if you have multiple logs you can number them for easier reading. And
\n
will add a blank line.
console.log(1, 'First message'); console.log('\n');Logs:
console.log(2, 'Second message');
1 'First message'
2 'Second message'
- Console.log is by far the most commonly used console method, but there are other methods you can use to be more specific as to the type of message you are logging.
- You can use console info, warn, or error methods. They do the same thing as console.log but may be displayed differently depending on the console application. For example the Chrome Dev Tools console displays console log and info with a white background, console.warn with a yellow background, and console.error with a red background.
console.info('Log info'); console.warn('This is a warning'); const err = new Error('This is an error');
console.error(err.toString());
- You can clear the console with the console.clear() method.
console.clear();
2. Location
- The location API represents the URL of the page it is called from.
- You can use it to get the full URL or parts of it by chaining the various properties listed below.
Example URL:
https://www.example.com:3000/users/361847
location.toString();
// "https://www.example.com:3000/users/361847" -- Returns the whole url as a string.location.href;
// Returns the whole url, same as toString()location.origin;
// "https://www.example.com:3000" -- Returns the whole url up to and excluding the path.location.protocol;
// "https:" -- Returns the protocol scheme.location.host;
// "www.example.com:3000/" -- Returns the host name and port.location.hostname;
// "www.example.com" -- Returns the host name.location.port;
// "3000" -- Returns the port number.location.pathname;
// "/users/361847" -- Returns the path and excludes query strings and fragments.
Example URL with query string and fragment:
https://www.example.com:3000/users?id=261847#address
location.search;
// "?id=261847" -- Returns the query string.location.hash;
// "#address" -- Returns the fragment identifier. Fragment is an element id on a web page.
location.reload();
// Reloads the current URL (Like browser refresh button).location.assign('url');
// Loads the URL you pass in as an argument.location.replace('url');
// Loads the URL you pass in as an argument. Like assign() except the current page won't be saved in session History.
3. History
- The History API lets you go back or forward to the previous or next page visited. It's like pressing the browser's back and forward buttons.
history.back();
// Go to the previous page in session history (like browser Back button).history.forward();
// Go to the next page in session history (like browser Forward button).
4. Web Storage
- On the backend, data can be stored in a database.
- On the frontend data can be stored in the browser in session storage, local storage, or cookie storage. We won't cover cookie storage here because it is set and retrieved from the server.
- Session and Local storage is set in your script.
- Data stored in Sessions persists until the browser window is closed.
- Data stored in LocalStorage persists indefinitely.
- Data is stored as key-value pairs and there are methods to:
- setItem('key', 'value'): Set an item by passing in the key and value.
- getItem('key'): Get an item by passing in the key.
- removeItem('key'): Remove an item by passing in the key.
- clear(): Clear all items.
Session Storage
- Session storage is used to store small amounts of data until the browser closes, then the session storage is cleared.
sessionStorage.setItem('name', 'Joey');
let name = sessionStorage.getItem('name'); name; // returns "Joey" sessionStorage.removeItem('name');
- The above example code calls the sessionStorage.setItem method to store a name value, "Joey", in the session.
- The second statement gets the name property from the sessionStorage.
- The last statement removes the name item from sessionStorage.
Example 2 - set, get, remove an object:
let user1String = JSON.stringify({ id: 1, name: 'Joey', active: true });
sessionStorage.setItem('user', user1String); user1String = sessionStorage.getItem('user');
const user1Obj = JSON.parse(user1String); sessionStorage.removeItem('user');
- Instead of storing a single value, you may want to store an object or an array. To save an object or array in sessionStorage, you can convert it to a string in JSON format using JSON.stringify.
- The first two statements above convert a user object to a JSON string and assigned to a variable. Then the sessionStorage.setItem() method adds it to session storage.
- The third and fourth statements retrieve the JSON string from session storage, then parses it, converting it from a JSON string to a JavaScript object.
- The last statement deletes the user item from session storage.
- To clear all items in sessionStorage, use:
sessionStorage.clear();
Local Storage
- Local storage persists indefinitely. The user can close their browser, then open it again, go back to the website, and the data is still there.
- Local Storage uses the same methods as session storage.
Example:
localStorage.setItem('name', 'Sheena');
name = localStorage.getItem('name'); name; // returns "Sheena" localStorage.removeItem('name');
- The first statement in the above example sets the 'name' item to 'Sheena'.
- The second statement gets the name value from localStorage.
- The last statement removes "name" from local storage.
- To clear all items in localStorage, use:
localStorage.clear();
4. Timers
- Now let's look at timers.
- There are a few timer Web APIs including setTimeout(), clearTimeout(), setInterval(), and clearInterval().
setTimeout
- The setTimeout function sets a timer which executes a function when the timer expires.
Format:
setTimeout(callbackFunction[, delayInMilliseconds]);
- It takes two arguments.
- The first argument is the function that executes after the timer expires.
- The second argument is the time delay in milliseconds. If left out, the callback function will execute immediately.
- The return value is a timeoutID number.
- The function executes asynchronously. When called, the script immediately goes to the next line without waiting for the timer to expire and the callback to execute. This is true even if the delay is 0.
Example:
setTimeout(() => {
console.log('Logs after 2 seconds');
}, 2000);
console.log('This logs first');
- Above is a simple example. The setTimeout function gets called with a delay of 2000 milliseconds (i.e., 2 seconds).
- The code immediately goes to the next line and logs "This logs first".
- After the two second delay the callback function is invoked. It prints: "Logs after 2 seconds".
setInterval
- The setInterval function repeatedly invokes the callback function, running the delay timer over and over again.
- Like setTimeout it takes two arguments: the callback function and the time delay in milliseconds.
- It returns a timeoutID number.
Format:
setInterval(callbackFunction, delayInMilliseconds);
Example:
let i = 1;
setInterval(() => {
console.log(i++);
}, 1000); // counter continues until page is closed
- The above setInterval function executes every 1000 milliseconds (i.e., every second). Variable i was initialized as 1, then every time the callback is invoked it increases i by one and logs it.
clearInterval
- To stop the setInterval function at some point you can use clearInterval.
- ClearInterval cancels the setInterval() function identified by the timeoutID.
Format:
clearInterval(intervalID)
Example:
i = 1;
const intervalID = setInterval(() => {
console.log(i++);
if (i === 6) clearInterval(intervalID);
}, 1000);
- Like the earlier example, the example above logs a number every second increasing it by one each time. It checks if the number is 6, and if so it calls the clearInterval function.
- As mentioned, the return value of the setInterval function is the intervalID. Use that as the argument for the clearInterval function and it will terminate setInterval when called.
5. Fetch
- The Fetch API provides an interface for fetching resources from the server or another URL.
- The fetch function has parameters for the URL to fetch from, and an optional options object:
fetch(url[, {options}]);
- Fetch is asynchronous and has Promises built into it. When fetch is called it immediately returns a pending Promise object. Then it sends an HTTP request over the internet to the URL provided. The promise resolves when the HTTP response is received.
- By default, fetch sends an HTTP GET request to get data from the server:
fetch('url');
- Fetch can also send data to the server by sending an HTTP POST request after a user fills out a form online. That is when you use the options argument, setting the method to "POST", and body to a data object in JSON format. The format is:
fetch('url', { method: 'POST', body: jsonData });
- Successful GET requests send a response with a body property containing the data, generally in JSON format.
- The Fetch API includes a .json() method that you chain to the response to extract the data from the response object and convert it from a JSON string to JavaScript.
- The
response.json()
method is also asynchronous, and returns a Promise that resolves to the parsed JSON data.
Example:
- We'll use an example of a web page with a button that, when clicked, fetches a list of users from an API, and displays them on the page when the data is received.
- Below is the HTML document.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<button id="btn">Get users</button>
<div id="result"></div>
<script src="webapis.js"></script>
</body>
</html>
- It contains:
- A button element with id="btn".
- An empty div element with id="result" to insert data.
- A script tag linking the HTML document to the webapis.js JavaScript file.
- Below is the JavaScript file.
webapis.js
const btn = document.getElementById('btn');
const result = document.getElementById('result');
// fetchData function
const fetchData = async (url) => {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`${res.status}`);
const data = await res.json();
return data;
}
catch (err) {
console.error(err.toString());
return false;
}
} // Listen for the click, call fetchData, handle result
btn.addEventListener('click', async () => {
const url = 'https://jsonplaceholder.typicode.com/users';
const users = await fetchData(url);
if (users) {
let names = '';
users.forEach((user) => names += `<li>${user.name}</li>`);
result.innerHTML = `<ul>${names}</ul>`
} else {
result.innerHTML = '<b>Could not fetch data.</b>';
}
});
- At the top it gets the "btn" button and result elements from the HTML page and assigns them to variables.
- The fetchData function: is a helper function. It is set up to be used generically for any fetch GET request.
const fetchData = async (url) => {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`${res.status}`);
const data = await res.json();
return data;
}
catch (err) {
console.error(err.toString());
return false;
}
}
- It takes a URL as the argument.
- Uses Fetch to get the data. Fetch uses Promises (covered in a separate tutorial) so it returns a pending promise when called, then returns the fulfilled promise with data when the response is returned. To wait for the response before moving on you need to put the async keyword before the function declaration and await before the fetch call.
- When the response comes back it has an ok property. If there was some problem such as an invalid domain name, ok will be false. If ok is false then we create and throw a new Error object.
- If the response is ok, then we call the .json() method on the response to convert it to JavaScript, then return it as the result.
- We wrapped the fetch call in a try...catch statement. If an error is thrown we catch it, then print it to the console. And return false.
- The listener function: listens for the click event, calls fetchData, and handles the result.
btn.addEventListener('click', async () => {
const url = 'https://jsonplaceholder.typicode.com/users';
const users = await fetchData(url);
if (users) {
let names = '';
users.forEach((user) => names += `<li>${user.name}</li>`);
result.innerHTML = `<ul>${names}</ul>`
} else {
result.innerHTML = '<b>Could not fetch data.</b>';
}
});
- We attached the addEventListener method to the button, listening for the click event.
- When the button is clicked we invoke the asynchronous callback function.
- It calls fetchData() passing in a url.
- "https://jsonplaceholder.typicode.com/users" is the URL to a free API testing website. The users path returns an array of ten dummy user objects.
- Fetch is an asynchronous function so we need to make fetchData an asynchronous function by add the async keyword to it, and putting await in front of the fetch call.
- We assigned the result of the fetch call to a variable named users. If users has data in it then we create an empty string variable called names, and iterate over the users array putting each user name into a list element and appending it to names.
- When forEach finishes iterating over the array, we assign result.innerHTML to the list of names. The list will display on the web page.
- If the users variable is set to false then we assign result.innerHTML to "Could not fetch data."
Fetch with invalid URLs:
- If you change the url to the valid domain but an invalid path:
const url = 'https://jsonplaceholder.typicode.com/badpath';
- Then res.ok will be false, and the fetchData function will throw and catch the error.
- If you change the url to an invalid domain name:
const url = 'http://no-such-url.com';
- Then it will automatically throw an error which gets caught in the function.
- And that concludes this video on JavaScript Web APIs.
Conclusion
The topics in this tutorial correspond with the JavaScript CheatSheet WebAPIs category. Make sure you understand each topic so you can refer back to the CheatSheet when working on your own projects.If you have the CheatSheet desktop app and downloaded the JavaScript CheatSheet, then go through the flashcards for this category to the point where you can answer them all in order and shuffled.