Lecture Notes Of Day 29
JavaScript and Web APIs
Objective:
The goal of this lesson is to
introduce the concept of Web APIs and demonstrate how to interact with them in
JavaScript. You will learn how to use JavaScript’s fetch() method to retrieve
data from APIs, and explore how to use the Geolocation API and the Web Storage
API.
1. Introduction
to Web APIs
What is a Web API?
- A Web
API (Application Programming Interface) is a set of rules and
protocols that allow different software applications to communicate with
each other over the internet.
- Web
APIs are commonly used to interact with servers and retrieve data or
interact with services such as weather, geolocation, or user data.
- Examples
of Web APIs include Geolocation API, Web Storage API, and Fetch
API (for making HTTP requests).
In this lesson, we will look into
the following key APIs:
1.Fetch API – to
retrieve data from external sources.
2.Geolocation
API – to
retrieve the user's location.
3.Web
Storage API – to store data in the browser.
2. Using
the Fetch API to Retrieve Data from APIs
The fetch() API provides an easy
way to make network requests (HTTP requests) and handle responses
asynchronously.
Syntax of fetch()
fetch(url,
options)
.then(response => response.json()) // Parse
the response as JSON
.then(data => console.log(data)) // Handle
the response data
.catch(error => console.error('Error:',
error)); // Catch any errors
- url –
The URL of the API endpoint.
- options –
Optional parameters like HTTP method, headers, body, etc.
Example:
Fetching Data from an API
Suppose you want to fetch data
from a public API like JSONPlaceholder (https://jsonplaceholder.typicode.com)
to retrieve a list of users.
javascript
Copy code
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json()) // Parse the JSON response
.then(data => {
console.log(data); // Display the data in the console
})
.catch(error => {
console.error('Error fetching data:',
error);
});
Explanation:
- fetch('https://jsonplaceholder.typicode.com/users')
sends a request to the API URL.
- .then(response
=> response.json()) parses the response into a JavaScript object.
- .then(data
=> {...}) handles the data returned from the API.
- .catch(error
=> {...}) handles any errors that occur during the fetching process.
Important Note: Fetch
returns a Promise, which is why .then() and .catch() are used to handle
asynchronous operations.
3. Working
with the Geolocation API
The Geolocation API allows
you to get the user's geographical location (latitude, longitude). This is
useful for apps like maps, location-based services, and weather apps.
Getting
the User's Location
You can retrieve the user's
current location using navigator.geolocation.getCurrentPosition().
Syntax:
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
- successCallback:
This is a function that is called if the location is successfully
retrieved.
- errorCallback:
This function is called if there is an error (e.g., permission denied).
- options:
This is an optional object where you can specify additional options like
accuracy.
Example: Getting User Location
if
(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log('Latitude: ' + position.coords.latitude);
console.log('Longitude: ' + position.coords.longitude);
},
(error) => {
console.error('Error: ' + error.message);
}
);
} else {
console.log('Geolocation is not supported by
this browser.');
}
Explanation:
- navigator.geolocation.getCurrentPosition()
retrieves the user's current position.
- The position
object contains details such as coords.latitude and coords.longitude.
- The errorCallback
handles cases where the user denies location access or an error occurs.
Important Notes:
- Geolocation
API may require user consent to access location data.
- The getCurrentPosition()
method works asynchronously, so a callback function is needed to handle
the response.
4. Working
with the Web Storage API
The Web Storage API allows
you to store data locally in the browser. There are two main types of storage:
1.LocalStorage – data
persists even after the browser is closed.
2.SessionStorage – data
is stored for the duration of the page session (i.e., it is lost when the page
is closed).
LocalStorage
LocalStorage is useful for
storing small amounts of data that need to be persistent across page reloads.
Example: Storing and Retrieving Data in LocalStorage
//
Storing data
localStorage.setItem('username',
'john_doe');
let
username = localStorage.getItem('username');
console.log(username); // Output: john_doe
//
Removing data
localStorage.removeItem('username');
//
Clearing all data
localStorage.clear();
Explanation:
- localStorage.setItem('key',
'value') stores data with a specified key.
- localStorage.getItem('key')
retrieves data for the given key.
- localStorage.removeItem('key')
removes data for the specified key.
- localStorage.clear()
clears all stored data.
SessionStorage
SessionStorage is similar to
LocalStorage, but its data is only available for the duration of the page
session.
Example:
Using SessionStorage
// Storing data in sessionStorage
sessionStorage.setItem('sessionUser',
'Jane_Doe');
// Retrieving data
let
sessionUser = sessionStorage.getItem('sessionUser');
console.log(sessionUser); // Output: Jane_Doe
// Clearing sessionStorage
sessionStorage.clear();
Explanation:
- The
methods for sessionStorage are the same as localStorage, but the data is
cleared when the page is closed or the browser tab is closed.
5. Combining
the Fetch API, Geolocation, and Web Storage
You can combine all these APIs in
a real-world scenario. For example, you could fetch weather data from an API,
get the user's location using Geolocation, and then store their preferences
using Web Storage.
Example:
Storing and Using User's Location for Weather Data
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
// Fetch weather data from an API using
the user's location
fetch(`https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=${latitude},${longitude}`)
.then(response => response.json())
.then(data => {
console.log(data);
localStorage.setItem('weatherData', JSON.stringify(data));
})
.catch(error => console.error('Error
fetching weather data:', error));
},
(error) => {
console.error('Error fetching location:',
error);
}
);
} else {
console.log('Geolocation is not supported by
this browser.');
}
Summary
- Web
APIs provide a way for JavaScript to interact with
the browser and other external services, enabling functionality like
retrieving data from remote servers, accessing user location, and storing
data locally.
- The Fetch
API allows you to make network requests to external APIs and handle
responses asynchronously.
- The Geolocation
API lets you retrieve the user's geographical location, which can be
useful for location-based services.
- The Web
Storage API enables you to store and retrieve data locally in the
browser using localStorage and sessionStorage.
By understanding these Web APIs,
you can build more interactive and dynamic web applications that can
communicate with external services and store data efficiently.
Key
Takeaways:
- Use fetch()
to retrieve data from APIs.
- Access
the user’s location using the Geolocation API.
- Store
and retrieve data locally using Web Storage API (localStorage and sessionStorage).
