Web API Introduction

Understanding browser APIs for modern web development

🌐 What are Web APIs?

Web APIs (Application Programming Interfaces) are built-in browser features that allow JavaScript to interact with the browser and device capabilities. They provide ready-to-use functions for common tasks.


// Simple Web API example - getting current page URL
console.log("Current page:", window.location.href);

// Getting browser information
console.log("Browser:", navigator.userAgent);
                                    

Output:

Current page: https://example.com/page.html

Browser: Mozilla/5.0 (Windows NT 10.0; Win64; x64)...

Common Web APIs

📍

Geolocation API

Get user's location coordinates

navigator.geolocation.getCurrentPosition()
💾

Storage API

Store data in the browser

localStorage.setItem('name', 'John')
🌐

Fetch API

Make HTTP requests to servers

fetch('https://api.example.com/data')

Web Workers

Run JavaScript in background

new Worker('worker.js')

🔹 How Web APIs Work

Web APIs are accessed through JavaScript objects provided by the browser:

// Window object - browser window information
console.log("Window width:", window.innerWidth);
console.log("Window height:", window.innerHeight);

// Document object - HTML document manipulation
document.title = "New Page Title";
document.body.style.backgroundColor = "lightblue";

// Navigator object - browser and device info
console.log("Online status:", navigator.onLine);
console.log("Language:", navigator.language);

Output:

Window width: 1920

Window height: 1080

Online status: true

Language: en-US

🔹 Simple API Example

Let's create a simple example using multiple Web APIs:

<!DOCTYPE html>
<html>
<head>
    <title>Web API Demo</title>
</head>
<body>
    <h1>Browser Information</h1>
    <button onclick="showInfo()">Show Browser Info</button>
    <div id="info"></div>

    <script>
    function showInfo() {
        const info = document.getElementById('info');
        info.innerHTML = `
            <p>Browser: ${navigator.appName}</p>
            <p>Platform: ${navigator.platform}</p>
            <p>Screen: ${screen.width}x${screen.height}</p>
            <p>Current Time: ${new Date().toLocaleString()}</p>
        `;
    }
    </script>
</body>
</html>

Output:

Browser Information

Browser: Netscape

Platform: Win32

Screen: 1920x1080

Current Time: 12/15/2024, 2:30:45 PM

🔹 Why Use Web APIs?

Benefits of Web APIs:

  • Built-in: No need to install external libraries
  • Standardized: Work the same way across browsers
  • Powerful: Access device features like camera, location
  • Efficient: Optimized by browser makers
  • Secure: Built with security considerations

🧠 Test Your Knowledge

What does API stand for?