Lesson 15 of 18

Fetch & APIs 🌎

🎯 Grades 9–12 ⏱ ~35 minutes 💚 Intermediate

What You'll Learn

  • Understand what an API is
  • Use the Fetch API to get data from the internet
  • Handle JSON data and display it on the page

What Is an API?

An API (Application Programming Interface) is a way for programs to talk to each other. A web API is a URL you can visit that returns data (usually JSON) instead of a webpage.

🍲
Real Example

Open this in your browser: https://api.open-meteo.com/v1/forecast?latitude=35.47&longitude=-97.52¤t=temperature_2m — That is live Oklahoma weather data as JSON!

The Fetch API

JavaScript
// Fetch returns a Promise
fetch('https://api.publicapis.org/entries?category=science')
  .then(response => response.json())  // parse JSON
  .then(data => {
    console.log(data);
    renderData(data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Async/Await (Cleaner Syntax)

JavaScript
async function getWeather() {
  try {
    const response = await fetch(
      'https://api.open-meteo.com/v1/forecast?latitude=35.47&longitude=-97.52&current=temperature_2m'
    );
    const data = await response.json();
    const temp = data.current.temperature_2m;

    document.getElementById('weather').textContent =
      `Current temp in OKC: ${temp}C`;
  } catch (error) {
    console.error('Failed to fetch:', error);
  }
}

getWeather();
💡
async/await

async/await is the modern way to handle fetch. It makes asynchronous code read like regular step-by-step code.

🌎">Live Weather Widget

Use the Open-Meteo API to fetch current weather for your city (look up latitude/longitude). Display the temperature on your page. Add a Refresh button that calls the function again!

Quick Check

What does fetch() return?

AAn array
BA Promise
CA string

What does response.json() do?

AConverts the response to a JSON file
BParses the response body as JSON
CSends JSON to the server

What does async/await do?

AMakes code run faster
BMakes asynchronous code look synchronous and easier to read
CPrevents errors in the code