7 min read
🔌intermediate

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

Now that you know what APIs and JSON are, let us actually fetch some data! JavaScript has a built-in function called fetch() that lets you make API requests right from your code. When you call fetch(), it returns a 'promise' — which is JavaScript's way of saying 'I will get back to you with the result, but it might take a moment.' This is because the request has to travel across the internet to a server and back, which takes time. We use the 'await' keyword to wait for the response before continuing.

Fetching Pokemon Data

javascript
// 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: electric

Handling Errors

API calls can fail for many reasons: the server is down, your internet is off, or the data does not exist. Good developers always handle errors. Common API errors: - 400 = Bad Request (you sent something wrong) - 401 = Unauthorized (you need an API key) - 404 = Not Found (that data does not exist) - 429 = Too Many Requests (you are calling too fast) - 500 = Server Error (something broke on their end) Always check the response status and handle failures gracefully so your app does not crash.

Fetching with Error Handling

javascript
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');
Pro Tip

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.

Build a Pokemon Card

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