Web APIs
What are APIs?
How do APIs work?
How do we debug APIs?
We'll start by looking at APIs from a high level —
what are they, how do they work, how do you use them in your code, and how are they structured?
We'll also take a look at what the different main classes of APIs are, and what kind of uses they have.
Web APIs
Application Programming Interfaces (APIs) are constructs made available in programming languages to allow
developers to create complex functionality more easily.
They abstract more complex code away from you, providing some easier syntax to use in its place.
Browser APIs
3rd Party APIs
Client-side JavaScript, in particular, has many APIs available to it — these are not part of the JavaScript
language itself, rather they are built on top of the core JavaScript language, providing you with extra
superpowers to use in your JavaScript code. They generally fall into two categories:
What are Browser APIs?
Animation
DOM
Canvas
WebGL
WebSocket
Browser APIs are built into your web browser and are able to expose data from the browser and surrounding
computer environment and do useful complex things with it. For example, the Geolocation API provides some simple
JavaScript constructs for retrieving location data so you can say, plot your location on a Google Map.
. In the background, the browser is actually using some complex lower-level code (e.g. C++) to communicate with
the device's GPS hardware (or whatever is available to determine position data), retrieve position data, and
return it to the browser environment to use in your code.
But again, this complexity is abstracted away from you by the API.
What are Third party APIs?
Smart
Bulb
Third party APIs are not built into the browser by default, and you generally have to grab their code and
information from somewhere on the Web.
For example, the Twitter API allows you to do things like displaying your latest tweets on your website.
We will use a third party api to access a smart light bulb.
How do APIs work?
Objects
Recognizable Entry Points
Events to handle changes in state
Security mechanisms
Different JavaScript APIs work in slightly different ways, but generally, they have common features and similar
themes to how they work.
They are based on objects.
APIs are interacted with in your code using one or more JavaScript objects, which serve as containers for the
data the API uses (contained in object properties),
and the functionality the API makes available (contained in object methods).
Entry points: When using an API, you should make sure you know where the entry point is for the API.
In The Geolocation API, this is pretty simple — it is the Navigator.geolocation property,
which returns the browser's Geolocation object that all the useful geolocation methods are available inside.
Security:
sometimes have additional security mechanisms in place.
For example, some of the more modern WebAPIs will only work on pages served over HTTPS due to them transmitting
potentially sensitive data (examples include Service Workers and Push).
Some WebAPIs request permission to be enabled.
Setup
Enable following experimental flags on chrome browser by typing chrome://flags on chrome.
Experimental JavaScript:
#enable-javascript-harmony
Experimental Web Platform features:
#enable-experimental-web-platform-features
Developer Tools experiments: #enable-javascript-harmony
Image Capture API: #enable-image-capture-api
chrome://flags/#enable-webvr
Network Information
enum ConnectionType {
"bluetooth",
"cellular",
"ethernet",
"mixed",
"none",
"other",
"unknown",
"wifi",
"wimax"
};
Network Information
enum EffectiveConnectionType {
"2g",
"3g",
"4g",
"slow-2g"
};
Network Information
interface NetworkInformation : EventTarget {
readonly attribute ConnectionType type;
readonly attribute EffectiveConnectionType effectiveType;
readonly attribute Megabit downlinkMax;
readonly attribute Megabit downlink;
readonly attribute Millisecond rtt;
readonly attribute boolean saveData;
attribute EventHandler onchange;
};
The "saveData" attribute, when getting, returns true if the user has requested a reduced data usage mode from
the user agent, and false otherwise.
Network Information
navigator.connection.addEventListener('change', changeHandler);
Bluetooth & Bluetooth Low Energy
Heart monitors
Fitbit
Sensors
Bluetooth can handle a lot of data, but consumes battery life quickly and costs a lot more.
BLE is used for applications that do not need to exchange large amounts of data, and can therefore run on
battery power for years at a cheaper cost.
It all depends on what you’re trying to accomplish.
Bluetooth
Bluetooth
navigator.bluetooth.requestDevice(options);
navigator.bluetooth.requestDevice({acceptAllDevices:true});
Bluetooth
navigator.bluetooth.requestDevice(options)
.then(device => {
console.log('Yay!I found your device: ' + device.name)
});
Bluetooth
navigator.bluetooth.requestDevice(options)
.then(device => {
device.gatt.connect())
};
Once you have the device you can use its gatt server to connect to it.
Device Orientation
Geolocation API
Geolocation
Position
Coordinates
Geolocation
Geolocation.getCurrentPosition(success, error?, [options]):
enableHighAccuracy = booleanValue
timeout (milliseconds)
maximumAge (milliseconds)
Geolocation.watchPosition()
Geolocation.clearWatch()
PositionOptions.enableHighAccuracy:
Is a Boolean that indicates the application would like to receive the best possible results.
If true and if the device is able to provide a more accurate position, it will do so.
Note that this can result in slower response times or increased power consumption (with a GPS chip on a mobile
device for example).
On the other hand, if false, the device can take the liberty to save resources by responding more quickly and/or
using less power. Default: false.
PositionOptions.maximumAge:
Is a positive long value indicating the maximum age in milliseconds of a possible cached position that is
acceptable to return.
If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current
position.
If set to Infinity the device must return a cached position regardless of its age. Default: 0.
Geolocation.watchPosition():
The Geolocation method watchPosition() method is used to register a handler function that will be called
automatically each time the position of the device changes.
This method returns a watch ID value that then can be used to unregister the handler by passing it to the
Geolocation.clearWatch() method.
Geolocation
const options = {
enableHighAccuracy: false,
timeout: 5000,
maximumAge: 0
};
functions success(position) {};
function error(err) {};
const watchId = navigator.geolocation.watchPosition(success, error, options);
navigator.geolocation.clearWatch(watchId);
Data Management APIs
Persistent Storage
Temporary Storage
Persistent: This is data that is intended to be kept around for a long time. This will only be evicted if the
user chooses to (for example in Firefox you can choose to delete all stored data or only stored data from
selected origins by going to Preferences and using the options under Privacy & Security > Cookies & Site Data.)
Temporary: This is data that doesn't need to persist for such long time . This will be evicted under a least
recently used (LRU policy) when Storage limits are reached.
Storage is temporary by default; developers can choose to use persistent storage for their sites using the
StorageManager.persist() method available in the Storage API.
There are limits to the amount of data you can store using client-side storage APIs (possibly both per
individual API and cumulatively);
the exact limit varies depending on the browser and possibly based on user settings. See Browser storage limits
and eviction criteria for more information.
consists of JavaScript APIs that allow you to store data on the client (i.e. on the user's machine) and then
retrieve it when needed.
This has many distinct uses, such as:
Personalizing site preferences (e.g. showing a user's choice of custom widgets, color scheme, or font size).
Persisting previous site activity (e.g. storing the contents of a shopping cart from a previous session,
remembering if a user was previously logged in).
Saving data and assets locally so a site will be quicker (and potentially less expensive) to download, or be
usable without a network connection.
Saving web application generated documents locally for use offline
Past:Cookies
Current: Web Storage and IndexedDB
Future: Cache API
Cookies:
The concept of client-side storage has been around for a long time. Since the early days of the web, sites have
used cookies to store information to personalize user experience on websites. They're the earliest form of
client-side storage commonly used on the web.
Because of that age, there are a number of problems — both technical and user experience-wise — afflicting
cookies.
These problems are significant enough that upon visiting a site for the first time, people living in Europe are
shown messages informing them if they will use cookies to store data about them.
This is due to a piece of European Union legislation known as the EU Cookie directive.
The only advantage cookies have is that they're supported by extremely old browsers.
Q: Why are there still new sites being created using cookies? This is mostly because of developers' habits, use
of older libraries that still use cookies, and the existence of many web sites providing out-of-date reference
and training materials to learn how to store data.
WebStorage:
he Web Storage API provides a very simple syntax for storing and retrieving smaller,
data items consisting of a name and a corresponding value. This is useful when you just need to store some
simple data,
like the user's name, whether they are logged in, what color to use for the background of the screen, etc.
IndexedDB API: provides the browser with a complete database system for storing complex data.
This can be used for things from complete sets of customer records to even complex data types like audio or
video files.
Cache API is designed for storing HTTP responses to specific requests,
and is very useful for doing things like storing website assets offline so the site can subsequently be used
without a network connection.
Cache is usually used in combination with the Service Worker API, although it doesn't have to be.
Web Storage API
Session Storage
Local Storage
localStorage.setItem('name','Aysegul');
var myName = localStorage.getItem('name');
localStorage.removeItem('name');
Open Chrome Dev Tools > Application > Storage > Local Storage
There is a separate data store for each domain (each separate web address loaded in the browser).
You will see that if you load two websites (say google.com and amazon.com) and try storing an item on one
website,
it won't be available to the other website.
TODO: Exercise: personalized page. Forget me button!
Session Storage
Cleared when the user session is over
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key');
// Remove all saved data from sessionStorage
sessionStorage.clear();
Local Storage
Limited to ~10 MB per origin
Cleared upon exiting on Incognito mode
Since localStorage and sessionStorage are instances, they do not support prototyping. However, Storage API
supports prototyping.
IndexedDB
Good for large amounts of structured data that requires high performance retrieval
Operations as done asynchronously as opposed to the synchronous Storage API.
Storage limit is browser and client dependent.
You can create indexes based on multiple properties of objects resulting in fast query times.
Intended to power offline webapps.
IndexedDB
dexie.js: A wrapper for IndexedDB that allows much faster code development via nice, simple syntax.
ZangoDB: A MongoDB-like interface for IndexedDB that supports most of the familiar filtering, projection,
sorting, updating and aggregation features of MongoDB.
JsStore: An IndexedDB wrapper with SQL like syntax.