The Front-End
JavaScript
Web APIs

Introduction to Web APIs: Browser APIs, localStorage, sessionStorage, and Third-Party APIs

  1. Working with Browser APIs
  2. Working with Browser APIs (localStorage, sessionStorage)
  3. Introduction to Third-Party APIs

Working with Browser APIs (localStorage, sessionStorage)

localStorage:

localStorage is a part of the Web Storage API, allowing web applications to store key-value pairs in a web browser with no expiration time. This data persists even when the browser is closed and reopened.

Example:

// Storing data in localStorage
localStorage.setItem("username", "John");
 
// Retrieving data from localStorage
const storedUsername = localStorage.getItem("username");
console.log(storedUsername); // Outputs: John

sessionStorage:

sessionStorage is similar to localStorage but has a shorter lifespan. The stored data is only available for the duration of the page session. Once the user closes the tab or window, the data is cleared.

Example:

// Storing data in sessionStorage
sessionStorage.setItem("language", "JavaScript");
 
// Retrieving data from sessionStorage
const storedLanguage = sessionStorage.getItem("language");
console.log(storedLanguage); // Outputs: JavaScript

Introduction to Third-Party APIs

Third-party APIs (Application Programming Interfaces) are interfaces provided by external services, allowing developers to access specific functionality or data. Commonly, third-party APIs provide a way to integrate services like social media platforms, payment gateways, or data services into your web applications.

Example: Using the OpenWeatherMap API

The OpenWeatherMap API provides weather data. To use this API, you typically need to sign up for an API key.

const apiKey = "YOUR_API_KEY";
const city = "New York";
 
// Fetching weather data from OpenWeatherMap
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`)
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
    // Process and display weather data
  })
  .catch(error => {
    console.error("Error:", error);
  });

This example demonstrates how to fetch weather data from the OpenWeatherMap API using the Fetch API. Ensure you replace "YOUR_API_KEY" with your actual API key.

Web APIs, both those provided by browsers and third-party services, are essential for building dynamic and feature-rich web applications. They empower developers to extend the functionality of their applications, interact with external services, and provide a more engaging user experience. Understanding how to work with browser APIs and integrate third-party APIs is a key skill for modern web development.