JS Fetch and API’s
For Web Dev 11
Review: JS Objects
Objects allow you to store different types of information within one variable.
// Create an object:
let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
// Display the name and age in a webpage
let elem = document.getElementById("demo");
elem.innerHTML = person.firstName + " is " + person.age + " years old.";
JSON
JSON - Javascript Object Notation is a way of storing text data
It uses the same syntax as JavaScript Objects
Example:
{
"name" : "Jason",
"age" : "24",
"hometown" : "Missoula, MT",
"gender" : "male"
}
JSON Examples
Array of objects
[{
"name" : "Jason",
"age" : "16",
"grade" : "11"
},
{
"name" : "Kyle",
"age" : "17",
"grade" : "12"
}];
Nested JSON
{
"jason" : {
"name" : "Jason Lengstorf",
"age" : "24",
"gender" : "male"
},
"kyle" : {
"name" : "Kyle Lengstorf",
"age" : "21",
"gender" : "male"
}
}
Content API’s
Activity API
The Activity API is a simple API that suggests activities for you to do.
https://mdinfotech.net/api/activity/
This is a sample response =>
{
"activity":"Write a poem",
"Type":"creative",
"Participants":1,
"Cost":"free"
}
How to Put API Content In Your Website
URL for API
Assign html elements to global variables
Fetch data from url
Convert the JSON in the response to a JavaScript Object
data is the JS Object containing the data from the URL. Pass it to updateWebsite.
Print the data to the console so you can see what it looks like. Use this to figure out how to access the information.
Put the data you want in your website
Global variables
let typeDiv;
window.onload
Global variables
Allows you to execute code once the page has finished loading in the browser
Are visible to the whole script
Assign html elements to global vars after the page is finished loading.
window.onload = function() {
someVar = document.getElementById(“someid”);
} // window.onload
Async/await
When programming, you often need to handle tasks that take time, like fetching data, reading files, or waiting for a timer. These tasks are called asynchronous tasks because they don't block other parts of your program.
To manage asynchronous tasks more easily, use async and await.
async
await
Error Handling: Use try...catch blocks to handle errors cleanly.
async/await
async function fetchContent() {
try {
// Send a GET request to the API
const response = await fetch(apiURL);
// Convert the response to JSON format
const data = await response.json();
console.log(data);
changeContent(data);
} catch (error) {
console.error('Error fetching activity:', error);
}
} // fetchContent