JavaScript
Tutorial: consuming an API with fetch - live data
Learn to use fetch to request data from the internet and display it on your page.
So far your pages only used data you typed yourself. Today we're going to ask the internet for data, live, using fetch. Welcome to the real world.
Step 1: make your first request
fetch('https://api.github.com/users/octocat')
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error('Something went wrong:', error));
fetch(url) requests data from that address. The response arrives in a format you need to convert to JSON with .json() (which, surprise, is also asynchronous, hence the extra .then). If something fails (no internet, the API is down), .catch warns you instead of silently breaking your page.
Step 2: the modern version with async/await
async function getUser() {
try {
const response = await fetch('https://api.github.com/users/octocat');
const data = await response.json();
console.log(data.name, data.public_repos);
} catch (error) {
console.error('Something went wrong:', error);
}
}
getUser();
async/await is the same idea as .then(), but reads top to bottom like normal code instead of nesting like a Russian doll. try/catch plays the same role as .catch(): catching errors before they blow up in the console.
Step 3: show the data on the page
<div id="user"></div>
async function displayUser() {
const response = await fetch('https://api.github.com/users/octocat');
const data = await response.json();
document.querySelector('#user').innerHTML = `
<h3>${data.name}</h3>
<p>Public repos: ${data.public_repos}</p>
`;
}
displayUser();
Now your page isn't stuck with fixed data: it shows real, up-to-date information that doesn't even live on your computer. That's, technically, 90% of what modern web apps do.
What did you just learn?
- How to request data from the internet with
fetch. - The difference between
.then()andasync/await(same idea, different syntax). - How to handle errors with
try/catchso your app doesn't break silently.