Fetching Data from an API — Your First API Call
Learn how to use JavaScript's fetch function to get real data from APIs and display it on a web page.
Making Your First API Call
Fetching Pokemon Data
// Fetch data about Pikachu from the Pokemon API
async function getPokemon(name) {
const response = await fetch(
'https://pokeapi.co/api/v2/pokemon/' + name
);
const data = await response.json();
console.log('Name:', data.name);
console.log('Height:', data.height);
console.log('Weight:', data.weight);
console.log('Types:', data.types.map(t => t.type.name).join(', '));
}
getPokemon('pikachu');
// Output:
// Name: pikachu
// Height: 4
// Weight: 60
// Types: electricHandling Errors
Fetching with Error Handling
async function getPokemonSafe(name) {
try {
const response = await fetch(
'https://pokeapi.co/api/v2/pokemon/' + name
);
if (!response.ok) {
throw new Error('Pokemon not found! Status: ' + response.status);
}
const data = await response.json();
return data;
} catch (error) {
console.log('Oops! ' + error.message);
return null;
}
}
// This works:
getPokemonSafe('pikachu');
// This handles the error gracefully:
getPokemonSafe('notarealpokemon');The 'async/await' syntax is modern JavaScript for handling operations that take time (like API calls). The 'async' keyword goes before the function, and 'await' goes before any operation that needs to wait. Under the hood, it uses Promises, but async/await is much easier to read and write.
Create an HTML page with an input field and a button. When the user types a Pokemon name and clicks the button, fetch that Pokemon's data from pokeapi.co and display a card showing: the Pokemon's name, an image (use data.sprites.front_default for the image URL), its types, and its base stats. Add error handling so that if someone types a fake Pokemon name, it shows a friendly error message instead of crashing!
Ready to build?
Put what you learned into practice — pick a project and start coding.
Start Building Free