API's and how they are used
Learn how API's work and how to implement one
- Web APIs
- Web APIs include methods and properties that extend functionalities of a browser
- Uses:
- Browser APIs
Web APIs
What is Web API?
- API stands for Application Programming Interface.
- A Web API is an application programming interface for the Web.
- A Browser API can extend the functionality of a web browser.
- A Server API can extend the functionality of a web server.
Web APIs include methods and properties that extend functionalities of a browser
Example:
%%js
const myArray = new Uint32Array(10);
crypto.getRandomValues(myArray);
console.log(myArray)
<IPython.core.display.Javascript object>
Explanation:
This web API creates a typed array of 10 integers called Uint32Array
It then fills it in with random values using crypto.getRandomValues(myArray);
console.log(myArray)
prints out the random values
Uses:
This is useful for security, where it would generate random cryptographic keys
Browser APIs
All browsers have a set of built-in Web APIs to support complex operations, and to help accessing data.
For example, the Geolocation API can return the coordinates of where the browser is located.
Example:
// Gets latitude and longitude of user's position
%%js
const myElement = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
myElement.innerHTML = "User denied geolocation";
}
}
function showPosition(position) {
myElement.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
This following code checks if the Geolocation API is in the user’s browser, and if it is it uses getCurrentPosition()
to find the user’s location. It then displays the latitude and longitude.
More APIs:
1. Fetch API - Making HTTP Requests
%%js
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await response.json();
console.log('Fetched data:', data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();
<IPython.core.display.Javascript object>
The Kernel crashed while executing code in the current cell or a previous cell.
Please review the code in the cell(s) to identify a possible cause of the failure.
Click <a href='https://aka.ms/vscodeJupyterKernelCrash'>here</a> for more info.
View Jupyter <a href='command:jupyter.viewOutput'>log</a> for further details.
This is a fetch API and it declares an asynchronous function.
- Asynchronous functions return a promise and are useful for handeling things that take time (Like API calls!).
fetch()
is a web API used to make HTTP requests (eg, GET, POST, DELETE), and this one sends a GET request to the JSONPlaceholder API. await
means the function will pause until the response is recived.
The data is then converted from HTTP to JSON in const data = await response.json();
, which sends structured data on web. This also uses await
because .json()
returns a promise.
console.log('Fetched data:', data')
prints the data to a browser console, and it would look something like this:
Fetched data:
{userId: 1, id: 1, title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', body: 'quia et suscipit\nsuscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto'}
body
:
"quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
id
:
1
title
:
"sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
userId
:
1
[[Prototype]]
:
Object
2. Local Storage API - Storing Data Locally
%%js
// Store data
localStorage.setItem('username', 'pika43');
localStorage.setItem('theme', 'dark');
// Retrieve data
const username = localStorage.getItem('username');
const theme = localStorage.getItem('theme');
console.log('Username:', username);
console.log('Theme:', theme);
This is a Web Storage API, specifically localStorage, and it is used to store and retrive data in the browser.
localStorage is covered in the other lesson so the explanation will be brief.
In this example a username is set to ‘pika43’, and the theme is set to ‘dark’.
const username = localStorage.getItem('username')
and const theme = localStorage.getItem('theme')
are used to retrive the values for the key username and theme.
the console.log
displays the username and theme.
3. Canvas API - Drawing Graphics
%%js
// Create a canvas element
const canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 200;
document.body.appendChild(canvas);
// Get the context
const ctx = canvas.getContext('2d');
// Draw a circle
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.stroke();
<IPython.core.display.Javascript object>
This uses the canvas API, which draws graphics on a canvas
element using JS.
In the example above a 200x200 pixel canvas is created, and is added to the page.
const ctx = canvas.getContext('2d')
gets 2d rendering context ctx
from the canvas.
The code after that is responsible for drawing a circle, with its center at (100,100), the radius is 50, and makes it a blue color.
Why use APIs?
There are multipule reasons for why a webpage would use an API
- To access External Data
- APIs let webpages display data from somewhere else
- To communicate with servers
- APIs let websites send and recive information from backend servers
- To use browser or device features
- The browser has Web APIs that can allow pages to do things such as access your geolocation, use the camera, or store data in localStorage
- To keep page dynamic
- APIs allow asynchronous communication, so pages can update content without refreshing, such as in discord (everyone here uses discord right? if not slack), you do not need to refresh the page every time you want to view a new message.
- To connect with third party services
- Websites might use APIs from other companies so they can save effort, such as Google Maps uses APIs to embed maps
Homework!!!!
Your homework is to create a simple currency converter using JS and an exchange rate API. We used https://freecurrencyapi.com/ however you could use whatever API you want.
You can make this into a page, and it does not have to be in the repository. You can create a new repository or put it in your personal blog
Requirements:
- YOU MUST USE AN API (eg, no using a fixed exchange rate such as 1 USD=7.34 CNY)
- You should have a minimum of 2 conversions, (USD to EUR and EUR to USD count as 1 each with a total of 2)
- make it look nice, such as not have it just be markdown (why we used HTML)