This code uses the fetch() function to get the JSON from https://happycoding.io/api/etsy-listings.json and then builds some HTML thumbnails from the data.
async function getEtsyListings() {
const containerDiv = document.getElementById('etsy-listings');
const response = await fetch('https://happycoding.io/api/etsy-listings.json');
const listings = await response.json();
const indexes = [];
while (indexes.length < 6) {
const index = Math.floor(Math.random() * listings.length);
if (!indexes.includes(index)) {
indexes.push(index);
}
}
for (const index of indexes) {
const listing = listings[index];
containerDiv.appendChild(buildEtsyThumbnail(listing));
}
}
function buildEtsyThumbnail(listing) {
const div = document.createElement('div');
div.classList.add('etsy-thumbnail');
div.innerHTML += `<a href="${listing.url}"><img src="${listing.imageSmallUrl}" /></a>`;
div.innerHTML += `<a href="${listing.url}">${listing.title}</a>`;
return div;
}
See the Pen by Happy Coding (@KevinWorkman) on CodePen.
fetch()
function to get data from it, and then build a webpage based on that data.Use the fetch function to get data from an API.
Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!
Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!