JavaScript Web Api Intro

In JavaScript, Web APIs enable you to interact with the browser and other services to perform tasks such as fetching data, manipulating the DOM, and handling user input.

What is a Web API?

A Web API (Application Programming Interface) allows applications to communicate with external services over the internet.

It defines a set of rules and protocols for accessing web-based services.

// Example: Fetching data from a Web API
fatch("https://api.example.com/data")
.then(response => response.json());
.then(data => console.log(data));
.catch(error => console.error("Error: ", error));

The Fetch API

The Fetch API provides a modern way to make HTTP requests in JavaScript.

It returns promises and is easier to use than the older XMLHttpRequest.

It allows you to fetch resources asynchronously across the network.

// Example: Using Fetch API to get data
fatch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.Json());
.then(posts => {
  posts.forEach(post => { 
    console.log(`Title: ${post.title}`);
    console.log(`Body: ${post.body}`);
  })
})
.catch(error => console.error("Error: ", error));

The DOM API

The Document Object Model (DOM) API allows JavaScript to interact with the HTML and CSS of a webpage.

It provides methods to traverse, modify, and listen to events on the document's elements.

// Example: Using DOM API to change content
document.getElementById("myButton").addEventListener('click', () => {
  document.getElementById("myText").textContent = "Button Clicked!";
})

The Geolocation API

The Geolocation API allows the browser to access the geographical location of the device.

It can be used to build location-aware applications such as maps and location-based services.

// Example: Using Geolocation API to get current position
if (navigator.geolocation) { 
  navigator.geolocation.getCurrentPosition(position => { 
    console.log(`Latitude: ${position.coords.latitude}`);
    console.log(`Longitude: ${position.coords.longitude}`);
  })
}else {
  console.log("Geolocation is not supported by this browser.");
}

The Web Storage API

The Web Storage API provides mechanisms to store key-value pairs in the browser.

It includes localStorage, which stores data with no expiration date, and sessionStorage, which stores data for the duration of the page session.

// Example: Using localStorage to store and retrieve data
localStorage.setItem("username" , "JaneDoe");
let username = localStorage.getItem("username");
console.log(username); // Outputs: JohnDoe

// Example: Using sessionStorage to store and retrieve data
sessionStorage.setItem("sessionData" , "12345");
let sessionData = sessionStorage.getItem("sessionData");
console.log(sessionData);; // Outputs: 12345

The Canvas API

The Canvas API provides a way to draw graphics and animations on a web page.

It is commonly used for creating games, visualizations, and other graphic-intensive applications.

// Example: Using Canvas API to draw a rectangle
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(10,10,150,100);

The WebSockets API

The WebSockets API enables real-time communication between the browser and a server.

It is useful for applications that require constant data exchange, such as chat applications and live updates.

// Example: Using WebSockets API to create a connection
const socket = new WebSocket("ws://example.com/socket");
socket.onopen = onopen => { 
  console.log("WebSocket connection opened");
  socket.send("Hello Server!");
}

socket.onmessage = event => { 
  console.log(`Message from server: ${event.data}`);
}

socket.onclose = () => { 
  console.log("WebSocket connection closed");
}

Web APIs in JavaScript provide powerful tools to enhance the functionality of web applications.

From fetching data asynchronously with the Fetch API to accessing device location with the Geolocation API, these interfaces enable developers to create dynamic and interactive web experiences.

Let's learn about the Form Api in the next chapter.