articles

Home / DeveloperSection / Articles / Explain the concept of Web APIs in JavaScript

Explain the concept of Web APIs in JavaScript

Explain the concept of Web APIs in JavaScript

Ashutosh Kumar Verma 33 26-Jun-2024

JavaScript Web API

Web APIs (Application Programming Interfaces) in JavaScript are interfaces provided by web browsers that allow developers to interact with the features and functionality of web browsers. This API is essential for web applications that can perform a wide range of tasks from manipulating the DOM (Document Object Model) to making HTTP requests and manipulating user input

Here are some basic features of Web APIs in JavaScript,

DOM Manipulation 

The Document Object Model (DOM) API enables JavaScript to interact with HTML and XML documents. Developers can access, modify, and manipulate the content of a web page using the methods provided by the DOM API. For example, you can select objects, change their attributes, or add new features dynamically.

Example-

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>JavaScript Web API Example</title>
</head>
<body>
    <div class="container my-4">
        <div class="row">
            <div class="col-12">
                <!-- element that text changed -->
                <p id="myElement">This is the Old text</p>
            </div>
        </div>
    </div>

    <script>
        // change the text of an element 
        let element = document.getElementById('myElement');
        element.textContent = 'This is the New text';         
    </script>
</body>
</html>

// output: This is the New text

 

AJAX and HTTP requests 

Web APIs such as XMLHttpRequest or the fetch API enable JavaScript to make HTTP requests to a server. You need to fetch data from external APIs, submit form data, or refresh an entire page and insert the information dynamically.

Example-

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>JavaScript Web API Example</title>
</head>
<body>
    <div class="container my-4">
        <div class="row">
            <div class="col-12">
                <!-- element that text changed -->
                <p id="Title"></p>
                <p id="BodyText"></p>
            </div>
        </div>
    </div>
    <script>

        // Example using fetch API to fetch data from a server
        fetch('https://jsonplaceholder.typicode.com/posts/1')
        .then(response => response.json())
        .then(json => {
            // bind the API data into html elements using id
            document.getElementById("Title").textContent = json.title;
            document.getElementById("BodyText").textContent = json.body;
        })
        // return if any error occured
        .catch(error => console.error('Error fetching data:', error));

    </script>
</body>
</html>

<!-- Output -->
sunt aut facere repellat provident occaecati excepturi optio reprehenderit

quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto

 

Also, Read: What is the FormData API in JavaScript, and how do you use it to send form data via an AJAX request?

 

Browser storage 

APIs such as localStorage and sessionStorage allow developers to store data locally in a user’s browser. This is useful for storing data, storing user preferences, or implementing offline functionality.

Example- 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>JavaScript Web API Example</title>
</head>
<body>
    <script>

        // Example using localStorage to store and retrieve data
        localStorage.setItem('username', 'Ashutosh Kumar');
        let username = localStorage.getItem('username');
        console.log('Username:', username); // Output: "Ashutosh Kumar"

    </script>
</body>
</html>

Note- If you want to verify the data that set on browser's localStorage then follow the steps- Open brower's Console (right-click in the tab -> inspect) -> Select Application tab -> Select Local storage in Storage option -> click on your file url -> see all the data that sets in local storage with key/value pairs

 

Geolocation

Geolocation APIs provide access to a user’s location, allowing web applications to customize content or provide geolocation services based on the user’s location

Example-

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>JavaScript Web API Example</title>
</head>
<body>
    <div class="container my-4">
        <div class="row">
            <div class="col-12">
                <!-- Latitude -->
                <p>Latitude: <span id="Latitude"></span></p>

                <!-- Longitude -->
                <p>Longitude: <span id="Longitude"></span></p>
            </div>
        </div>
    </div>
    <script>
    // Example using Geolocation API to get user's current position
    navigator.geolocation.getCurrentPosition(position => {
        document.getElementById("Latitude").textContent = position.coords.latitude;
        document.getElementById("Longitude").textContent = position.coords.longitude;  
    }, error => {
    console.error('Error getting location:', error);
    });

    </script>
</body>
</html>

<!-- Output -->
Latitude: 26.8466937
Longitude: 80.946166

Audio Video 

Audio Video and other APIs provide functions for playing and manipulating audio and video content directly on web browsers.

Example-

// Example using Audio API to play an audio file
let audio = new Audio('path/to/audio.mp3');
audio.play();

 

These are just a few examples of the many Web APIs available to JavaScript developers. Each API serves a specific purpose and extends web application capabilities beyond basic scripting and markup.

 

Also, Read: Prototypal Inheritance vs. Class-Based Inheritance in JavaScript


Updated 26-Jun-2024
Hi! This is Ashutosh Kumar Verma. I am a software developer at MindStick Software Pvt Ltd since 2021. I have added some new and interesting features to the MindStick website like a story section, audio section, and merge profile feature on MindStick subdomains, etc. I love coding and I have good knowledge of SQL Database.

Leave Comment

Comments

Liked By