Hey I am struggling to fetch an API. I just don’t get it to work.
<!DOCTYPE html>
<html>
<head>
<title>Sponsorkliks API Table</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<table id="api-table">
<thead>
<tr>
<th>Name</th>
<th>URL</th>
<th>Logo</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
fetch('https://www.sponsorkliks.com/api/?club=11592&call=webshops_club_extension')
.then(response => response.json())
.then(data => {
const tableBody = document.querySelector('#api-table tbody');
data.forEach(item => {
const row = document.createElement('tr');
const nameCell = document.createElement('td');
nameCell.textContent = item.name;
row.appendChild(nameCell);
const urlCell = document.createElement('td');
const urlLink = document.createElement('a');
urlLink.href = item.url;
urlLink.textContent = item.url;
urlCell.appendChild(urlLink);
row.appendChild(urlCell);
const logoCell = document.createElement('td');
const logoImg = document.createElement('img');
logoImg.src = item.logo;
logoImg.alt = item.name;
logoImg.style.maxWidth = '100px'; // adjust size if needed
logoCell.appendChild(logoImg);
row.appendChild(logoCell);
tableBody.appendChild(row);
});
})
.catch(error => console.error(error));
</script>
</body>
</html>
I would like to use the API above and would like to take data out if it. However, everything I tried so far did not work.
I tried a lot of different things to fetch the data. I have nevert worked with this before, so I can not figure it out.
2
Answers
You’re just not so focused on your data. You should iterate
data.webshops
and use different field names in a webshop object:I also don’t recommend adding elements with DOM, it’s slow, use pure html:
The problem is that data is supposed to be an array, but instead is an
Object {webshops: Array(694)}
. Changedata.foreach(item => {
toObject.values(item => {
. Then, loop through each of the arrays inside of the object and grab the data. However, while doing this, a I realized the objects take the form ofObject {category: "Gifts", name_short: "Sinterklaas-feestwinkel.nl", name_long: "Sinterklaas-feestwinkel.nl", description: "De Sinterklaas-feestwinkel.nl is er voor alle Sinterklaas inkopen, naast een grote assortiment Sinterklaas versiering en Sinterklaas en Zwarte pieten kostuums heeft deze winkel ook kado’s voor jong en oud. Hier vindt men alles voor een geslaagde Sinterklaas avond.", logo_120x60: "https://www.sponsorkliks.com/gfx/partners/sinterklaas-feestwinkel.png", …}
, so I think you were mistaken when you wrote url. Instead of url, I swapped it out for ‘description’, as shown below:However, watch out, since I disabled script escaping, so if the api has a hidden
<script>
tag, it would run and this would result in a code injection attack.