JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Web API Introduction


Web APIs are one of the most powerful parts of modern JavaScript. They allow your code to interact with the browser, system, or external services easily.
If you’ve ever used fetch() for data, localStorage for saving items, or addEventListener() for events — you’ve already used Web APIs.

What is a Web API?

API stands for Application Programming Interface.
A Web API is an interface that allows JavaScript to communicate with the browser’s built-in features or external web services.

In simple words:

Web APIs are tools that help your JavaScript code interact with the browser or web server.

Examples of Web APIs:

API Name Description
DOM API Works with HTML elements (create, delete, modify).
Fetch API Requests data from a server (replaces old XMLHttpRequest).
Geolocation API Gets user’s location.
History API Controls browser history.
Web Storage API Stores data in browser (localStorage, sessionStorage).
Canvas API Draws graphics and shapes.
Web Worker API Runs background tasks without blocking the main thread.
Notification API Shows system-style notifications.

Each of these APIs gives JavaScript access to specific browser functionality safely.

Browser vs. Third-Party APIs

There are two main types of Web APIs:

  1. Browser APIs – built into the browser (like fetch, localStorage, or navigator).

  2. Third-party APIs – provided by external websites or services (like YouTube API, OpenWeather API, or Google Maps API).

Example 1: Browser API (Local Storage)

// Save data using the Web Storage API
localStorage.setItem("username", "Vicky");

// Read data
console.log(localStorage.getItem("username"));

Explanation:
This uses the Web Storage API built into your browser. The data stays even after reloading.

Example 2: Third-Party API (Fetch Data from a Website)

// Fetch data from a fake API
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));

Explanation:

  • fetch() is part of the Fetch API, which lets you make HTTP requests.

  • It gets data from a URL and handles it using JavaScript promises.

How Web APIs Work

Web APIs act as a bridge between your JavaScript code and the browser or web service.

Here’s what happens step-by-step:

  1. JavaScript sends a request to an API (browser or server).

  2. The API processes the request.

  3. The API returns a response (data, message, or action).

  4. JavaScript uses that response in your webpage.

For example:

  • When you use the Fetch API, it requests data from a server.

  • When you use the DOM API, it changes what users see on the screen.

Common Built-in Web APIs in JavaScript

Let’s look at the most commonly used Web APIs:

1. DOM (Document Object Model) API

Works with HTML and CSS.

document.getElementById("demo").textContent = "Hello from DOM API!";

2. Fetch API

Used for making HTTP requests.

fetch("https://api.github.com/users/octocat")
.then(res => res.json())
.then(user => console.log(user.name));

3. Web Storage API

Stores key-value data in the browser.

localStorage.setItem("theme", "dark");

4. Geolocation API

Finds the user’s current location.

navigator.geolocation.getCurrentPosition(
    (position) => console.log(position.coords.latitude),
    (error) => console.error("Error getting location", error)
);

5. History API

Manages browser history (back, forward, state changes).

history.pushState({ page: 1 }, "Title 1", "?page=1");

6. Web Worker API

Runs background tasks.

let worker = new Worker("worker.js");

Why Web APIs Are Important

Web APIs make your web applications:

  • Interactive – using DOM, Events, Animations

  • Connected – using Fetch or WebSocket

  • User-friendly – using Geolocation, Notifications

  • Efficient – using Web Workers and Storage

Without APIs, JavaScript could only work with static content and not interact with the browser environment.

Real-world Use Cases

Here are some practical examples of where Web APIs are used daily:

Feature API Used Description
Show user’s location on map Geolocation API Get latitude and longitude.
Store login session Web Storage API Save data in localStorage.
Load latest news Fetch API Fetch data from server.
Handle form validation Validation API Check form fields before submission.
Control browser navigation History API Move forward or backward in history.
Display notifications Notification API Show popup alerts to users.

Combining Multiple APIs

You can combine multiple APIs for advanced tasks.

Example: Fetch + DOM + Local Storage

<p id="quote"></p>
<button onclick="loadQuote()">Load Quote</button>

<script>
function loadQuote() {
    fetch("https://api.quotable.io/random")
    .then(res => res.json())
    .then(data => {
        // Display quote using DOM API
        document.getElementById("quote").textContent = data.content;

        // Save quote using localStorage API
        localStorage.setItem("lastQuote", data.content);
    })
    .catch(() => alert("Error fetching quote"));
}
</script>

Explanation:

  • Uses Fetch API to get data.

  • Updates HTML using DOM API.

  • Saves the quote in localStorage.

This is how modern web apps use multiple APIs together to create smooth user experiences.

Checking API Support

Not all browsers support every API.
You should check if an API is available before using it.

if ("geolocation" in navigator) {
    console.log("Geolocation API supported!");
} else {
    console.log("Not supported in this browser.");
}

Tip: Always perform this check for better cross-browser compatibility.

Key Points to Remember

  • Web APIs are interfaces for browser features or web services.

  • There are two types: Browser APIs and Third-party APIs.

  • They can:

    • Modify HTML (DOM API)

    • Store data (Web Storage)

    • Fetch data (Fetch API)

    • Get location (Geolocation)

    • Manage history (History API)

  • Always check if an API is supported before using it.

Summary of the Tutorial

The Web API is what makes modern websites powerful, interactive, and dynamic.
From handling browser features to connecting external data, APIs help JavaScript communicate efficiently with everything around it.

You’ve already been using them — document, fetch, navigator, history — all are Web APIs.
Once you master them, you’ll be able to build responsive, interactive, and data-driven web apps easily.


Practice Questions

  1. Write a JavaScript program that uses the Web Storage API to save a user's name in localStorage and display it on the page after reload.

  2. Create a simple page that fetches a random joke from an API (https://official-joke-api.appspot.com/random_joke) using the Fetch API and displays the setup and punchline in separate paragraphs.

  3. Use the Geolocation API to get the user’s latitude and longitude and display them inside a <div> element.

  4. Write a JavaScript code that checks if the Fetch API is supported in the browser. If not, display a message saying "Your browser does not support Fetch API".

  5. Use the History API to change the browser URL to ?page=contact without reloading the page and log the new URL in the console.

  6. Write a code that combines the Fetch API and DOM API to load a list of users from https://jsonplaceholder.typicode.com/users and display their names in an ordered list.

  7. Use the Notification API to show a desktop notification saying “Welcome back to our site!” after the user clicks a button.

  8. Write JavaScript code that stores a dark mode preference using the Web Storage API. If dark mode is enabled, change the page background to black on the next load.

  9. Create a function that checks if the Geolocation API is supported in the user’s browser. If supported, log “Supported”, otherwise log “Not Supported”.

  10. Use the Fetch API to get a post from https://jsonplaceholder.typicode.com/posts/1 and store the post title in localStorage using the Web Storage API.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top