0% found this document useful (0 votes)
2 views

JavaScript Web APIS

The document provides an overview of JavaScript Web APIs, explaining what Web APIs are and detailing various types such as Browser APIs, Server APIs, and Third-party APIs. It covers specific APIs including the History API, Web Storage API, Forms API, Fetch API, and Geolocation API, along with examples of how to use them. Additionally, it highlights the differences between localStorage and sessionStorage, and discusses the importance of user permissions when accessing location data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JavaScript Web APIS

The document provides an overview of JavaScript Web APIs, explaining what Web APIs are and detailing various types such as Browser APIs, Server APIs, and Third-party APIs. It covers specific APIs including the History API, Web Storage API, Forms API, Fetch API, and Geolocation API, along with examples of how to use them. Additionally, it highlights the differences between localStorage and sessionStorage, and discusses the importance of user permissions when accessing location data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

JavaScript Web APIS

What is Web API?


• The API is an acronym for the Application Programming Interface. It is a standard protocol or set
of rules to communicate between two software components or systems.
• A web API is an application programming interface for web.
• The API provides an easy syntax to use the complex code. For example, you can use the Geo
Location API to get the coordinates of the users with two lines of code. You don’t need to worry
about how it works in the backend.
• Another real-time example you can take is of a power system at your home. When you plug the
cable into the socket, you get electricity. You don’t need to worry about how electricity comes into
the socket.
There are different types of web APIs, some are as follow −
• Browser API (Client-Side JavaScript API)
• Server API
• Third Party APIs
Browser API (Client-side JavaScript API)
• The browser APIs are set of Web APIs that are provided by the browsers.
• The browser API is developed on top of the core JavaScript, which you can use
to manipulate the web page's functionality.
• There are multiple browser APIs available which can be used to interact with
the web page.

Following is a list of common browser APIs −


Server API
• A server API provides different functionalities to the
web server. Server APIs allow developers to interact
with server and access data and resources.
• For example, REST API is a server API that allows us to
create and consume the resources on the server. A
JSON API is popular API for accessing data in JSON
format. The XML API is a popular API for accessing data
in XML format.
Third-party APIs
• The third-party API allows you to get the
data from their web servers. For example,
YouTube API allows you to get the data
from YouTubes web server.
Most third-party APIs are accessed via HTTP requests
(typically REST APIs):
// Example: Using the OpenWeatherMap API
const apiKey = 'YOUR_API_KEY';
const city = 'London';

fetch(`https://api.openweathermap.org/data/2.5/weather?q
=${city}&appid=${apiKey}&units=metric`)
.then(response => response.json())
.then(data => {
console.log(`Current temperature in ${city}:
${data.main.temp}°C`);
console.log(`Weather: ${data.weather[0].description}`);
})
.catch(error => console.error('Error fetching weather:',
error));
JavaScript Web API List
• Here, we have listed the most common web APIs.
Web History API
• In JavaScript, the history API allows us to access the browsers history. It can be
used to navigate through the history.
• JavaScript History API provides us with methods to manipulate window history
object. History object is a property of JavaScript window object. The window
history object contains the array of visited URLs in the current session
• The history API is very powerful tool to create may useful effects. For
example, we can use it to implement history based undo redo system.
How to use JavaScript History API?

The History API is a very simple API to use. There are just a few methods and a
property that you need to know about:
Syntax
• Followings are the syntaxes to use the different methods
and property of the history object −
Loading Previous Page in History List
• The JavaScript history back() method of the history object loads the previous URL in
the history list. We can also use the history go() method to load the previous page.
The difference between these two methods is that back() method only load the
immediate previous URL in history list but we can use the go() method to load any
previous URL in the history list.

Example: Using back() method to load previous page

In the example, we have used history back()


method to load the previous page the user has
already visited.
Please note that if you have no previous page in
the history list (i.e., you have not visited any page
previously), the back() method will not work.
We have implemented a back button, on clicking
that we can load the previous visited page.
Get the length of the history list
• We can use the history.length proerty to get the length
of history list.
• Try the follwing example −
What is Web Storage API?
• The web storage API in JavaScript allows us to store the data in the
user's local system or hard disk. Before the storage API was introduced
in JavaScript, cookies were used to store the data in the user's
browser.
• The main problem with the cookies is that whenever browsers request
the data, the server must send it and store it in the browser.
Sometimes, it can also happen that attackers can attack and steal the
data.
• In the case of the storage API, we can store the user's data in the
browsers, which remains limited to the user's device.
• JavaScript contains two different objects to store the data in the local.
The Window local Storage Object
• The localStorage object allows you to store the data locally in the key-value pair format in the
user's browser.
• You can store a maximum of 5 MB data in the local storage.
• Whatever data you store into the local storage, it never expires. However, you can use the
removeItem() method to remove the particular or clear() to remove all items from the local
storage.
Example
• In the below code, we set the 'fruit' as a key and 'Apple' as a value in the local storage inside the
setItem() function. We invoke the setItem() function when users click the button.
• In the getItem() function, we get the value of the 'fruit' key from the local storage.
• Users can click the set item button first and then get the item to get the key-value pair from the
local storage.

The local Storage doesn't allow you to


store the objects, functions, etc. So, you
can use the JSON.stringify() method to
convert the object into a string and
store it in the local storage.
Example: Storing the object in the local storage
• In the below code, we have created
the animal object. After that, we
used the JSON.stringify() method to
convert it into the string and store it
as a value of the 'animal' object.

• Users can click the set item button


to set the object into the local
storage and get the item button to
get the key-value pair from the local
storage.
Example: Removing the items from the local
storage
• In the below code, we set the 'name' and 'john' key-value pair in the local storage when the web
page loads into the browser.
• After that, users can click the get item button to get the item from local storage. It will show you
the name.
• You can click the get item button again after clicking the remove item button, and it will show you
null as the item got deleted from the local storage.
The Window session Storage Object
• The sessionStorage object also allows storing the data in the browser in the key-value pair format.
• It also allows you to store the data up to 5 MB.
• The data stored in the session storage expires when you close the tab of the browsers. This is the main
difference between the session storage and local storage. You can also use the removeItem() or clear() method
to remove the items from the session storage without closing the browser's tab.
• Note Some browsers like Chrome and Firefox maintain the session storage data if you re-open the browser's tab
after closing it. If you close the browser window, it will definitely delete the session storage data.
Example
• In the below code, we used the 'username' as a key and ‘webprogramming' as
a value. We store the key-value pair in the sessionStorage object using the
setItem() method.
• You can click the get item button after clicking the set item button to get the
key-value pair from the session storage.

You can't store the file or image data


directly in the local or session storage,
but you can read the file data, convert
it into the string, and store it in the
session storage.
Cookie Vs localStorage Vs sessionStorage
Storage Object Properties and Methods
Web Forms API
• JavaScript Forms API is a web API that allows us to interact with and
manipulate HTML forms. It provides a set of methods and properties that are
used to perform client-side form validation. Its also helpful to ensure data
integrity before form submission. The forms API also referred to as Form
Validation API or Constraint Validation API.
Contd..

Example: Using the checkValidity() method


We created the number input in the code and set
10 to the min attribute.
In the validateInput() function, we access the
number input using the id and use the
checkValidity() to validate the value of the
number input.
If checkValidity() method returns false, we print
the validation message. Otherwise, we print the
numeric value.
Constraint Validation DOM Properties
Properties of the 'validity' Property
In JavaScript, each element has the 'validity' property, containing multiple properties. You
can use the particular property of the 'validation' property to perform the validation.
Here, we have listed all properties of the 'validity' property.
Contd..

Example

In the below code, we have defined the number


input and set 300 for the value of the max
attribute.
In the validateNumber() function, we use the
rangeOverflow property of the validity property of
the input element to check whether the input
value is greater than 300.
If the rangeOverflow property returns true, we
print the Number is too large. Otherwise, we print
the numeric value.
What is a Fetch API?
• The JavaScript Fetch API is a web API that allows a web
browser to make HTTP request to the web server. In
JavaScript, the fetch API is introduced in the ES6 version. It
is an alternative of the XMLHttpRequest (XHR) object, used
to make a 'GET', 'POST', 'PUT', or 'DELETE' request to the
server.
• The window object of the browser contains the Fetch API by
default.
• The Fetch API provides fetch() method that can be used to
access resources asynchronously across the web.
• The fetch() method allows you to make a request to the
server, and it returns the promise. After that, you need to
resolve the promise to get the response received from the
server.
Contd..
Handling Fetch() API Response with
'then...catch' Block

Example
In the code in right hand side, we fetch the data
from the given URL using the fetch() API. It
returns the promise we handle using the 'then'
block.
First, we convert the data into the JSON format.
After that, we convert the data into the string and
print it on the web page.
Fetch with Async/Await (Modern Approach)

Example
In the code right hand side, we have defined the
getData()asynchronous function to fetch the to-do
list data from the given URL using the fetch() API.
After that, we convert the data into JSON and print
the output on the web page.
Options of Fetch API
Example: Making a GET Request
• In the below code, we have passed the "GET" method as an option to the fetch() API.
• Fetch () API fetches the data from the given API endpoint.
Advantages of Using the Fetch() API
Geolocation API
• The Geolocation API is a web API that provides a JavaScript interface to
access the user's geographical location data. A Geolocation API
contains the various methods and properties that you can use to
access the user's location on your website.
• It detects the location of the user's using the device's GPS. The
accuracy of the location depends on the accuracy of the GPS device.
• As location compromises the users' privacy, it asks for permission
before accessing the location. If users grant permission, websites can
access the latitude, longitude, etc.
• Sometimes, developers need to get the user's location on the website.
For example, if you are creating an Uber,Kakaotaxi etc. type
applications, you need to know the user's location to pick them up for
the ride.
• The Geolocation API allows users to share the location with a particular
website.
Real-time use cases of the Geolocation API
• Here are the real-time use cases of the Geolocation
API.
Using the Geolocation API
• To use the Geolocation API, you can use the 'navigator' property of the window object. The Navigator object
contains the 'geolocation' property, containing the various properties and methods to manipulate the user's
location.

Example: Checking the browser support


Using the navigator, you can check whether the
user's browser supports the
Geolocation.geolocation property.
The code right hand side prints the message
accordingly whether the Geolocation is supported.
First, we convert the data into the JSON format.
After that, we convert the data into the string and
print it on the web page.
Contd..
Getting User's Location
Geolocation Errors
Example: Error Handling

We use the getCurrentPosition() method in the


findLocation() function in the code right hand side.
We have passed the errorCallback() function as a
second parameter of the getCurrentPosition()
method to handle the errors.
In the errorCallback() function, we use the switch
case statement to print the different error
messages based on the error code.
When you click the Find Location button, it will
show you a pop-up asking permission to access
the location. If you click on the 'block, it will show
you an error.
First, we convert the data into the JSON format.
After that, we convert the data into the string and
print it on the web page.
Geolocation Options

Example
The code in the right hand side finds the most accurate
location. Also, we have set milliseconds to the maximum
Age, and timeout properties of the options object.
First, we convert the data into the JSON format. After that,
we convert the data into the string and print it on the web
page.
Watching the Current Location of the User
Example
• In the code right hand side, we used the
geolocation object's watchPosition ()
method to get the user's continuous
position.
• We used the getCords() function as a
callback of the watchPosition() method,
where we print the latitude and longitude
of the user's position.
• In the findLocation() method, we used the
setTimeOut() method to stop tracking after
30 seconds.
• In the output, you can observe that the
code prints the user's position multiple
times.
• First, we convert the data into the JSON
format. After that, we convert the data into
the string and print it on the web page.
Exercise

You might also like