Software EngineeringAlliance Girls High School
TERM 3 / LESSON 06

HOLIDAY SELF-STUDY · WEEK 2

APIs and Fetch

HOLIDAY SELF-STUDY · WEEK 2 · TUTORIAL

Fetch live weather.
Step by step.

Build a small weather widget with a free API, then add loading, empty and error states to your capstone.

  • TimeAbout 2–3 hours. Stop after any step and continue later.
  • ToolNitroIDE and Open-Meteo. No key or account needed.
  • GoalYour capstone loads data and never shows a blank screen.

Do each numbered step, compare with ✅ Check, then press → for the next slide. Written guide: Lesson 6 · Holiday Self-Study Pack.

01

STEP 1 OF 11 · LOOK AT REAL DATA

See what an API sends back.

  1. Open this link in a new tab: Open-Meteo Nairobi weather.
  2. Find "current", then "temperature_2m" inside it.
  3. Find "current_units". It holds the unit, °C.

response (shortened)

{
  "latitude": -1.25,
  "longitude": 36.8125,
  "current_units": {
    "temperature_2m": "°C"
  },
  "current": {
    "temperature_2m": 21.4
  }
}

✅ Check: a page of text (JSON) with Nairobi’s temperature right now. Your numbers will differ.

Your page sends a request; the API sends back a response in JSON.

02

STEP 2 OF 11 · INDEX.HTML

Start a practice project.

  1. In NitroIDE, click Prefs → Download ZIP to back up your capstone.
  2. Click Projects → New Project and delete the starter code.
  3. Type this into index.html.

index.html

<h1>Nairobi weather</h1>
<p id="weather-status" aria-live="polite"></p>
<button id="refresh" type="button">Refresh</button>

✅ Check: a heading and a Refresh button. No weather yet.

03

STEP 3 OF 11 · SCRIPT.JS

Save the API address.

  1. Click script.js.
  2. Type the address in three parts, exactly as shown.
  3. Select the status paragraph and the button.

script.js

const weatherUrl =
  "https://api.open-meteo.com/v1/forecast" +
  "?latitude=-1.2864&longitude=36.8172" +
  "&current=temperature_2m";

const status = document.querySelector("#weather-status");
const refreshButton = document.querySelector("#refresh");

✅ Check: the page has not changed and the Console shows no red errors.

latitude and longitude choose the place. current chooses the data.

04

STEP 4 OF 11 · SCRIPT.JS · ADD BELOW

Fetch the data.

  1. Add this function at the bottom.
  2. The last line runs it when the page opens.
  3. Watch the preview.

script.js · add at the bottom

async function loadWeather() {
  status.textContent = "Loading weather…";

  const response = await fetch(weatherUrl);
  const data = await response.json();

  const temp = data.current.temperature_2m;
  const unit = data.current_units.temperature_2m;
  status.textContent = `Nairobi: ${temp} ${unit}`;
}

loadWeather();

✅ Check: “Loading weather…” then something like Nairobi: 21.4 °C.

await waits for the internet. async lets a function use await.

05

STEP 5 OF 11 · SCRIPT.JS · REPLACE

Handle errors.

  1. Replace your whole loadWeather function with this version.
  2. Keep the loadWeather(); line below it.
  3. Watch the preview.

script.js · replace loadWeather

async function loadWeather() {
  status.textContent = "Loading weather…";
  try {
    const response = await fetch(weatherUrl);
    if (!response.ok) {
      throw new Error(`Request failed: ${response.status}`);
    }
    const data = await response.json();
    const temp = data.current.temperature_2m;
    const unit = data.current_units.temperature_2m;
    status.textContent = `Nairobi: ${temp} ${unit}`;
  } catch (error) {
    status.textContent = "Weather is unavailable. Please try again later.";
    console.error(error);
  }
}

✅ Check: the temperature still appears, exactly as before.

try runs the risky code. catch shows a friendly message if it fails.

06

STEP 6 OF 11 · SCRIPT.JS · ADD BELOW

Refresh, then break it.

  1. Add the line below at the bottom, then click Refresh.
  2. Now change forecast to forecastx in the address.
  3. Read the message on the page.
  4. Change it back to forecast.

script.js · add at the bottom

refreshButton.addEventListener("click", loadWeather);

✅ Check: a friendly error appears instead of a blank page, then the weather returns when you fix the address.

07

STEP 7 OF 11 · EXPERIMENT

Change the town.

  1. Pick a town from the list.
  2. Replace the latitude and longitude numbers in weatherUrl.
  3. Change “Nairobi” in the heading and in the status message.

coordinates

Mombasa   latitude=-4.0435   longitude=39.6682
Kisumu    latitude=-0.0917   longitude=34.7680
Nakuru    latitude=-0.3031   longitude=36.0800
Eldoret   latitude=0.5143    longitude=35.2698

✅ Check: the temperature for your new town appears.

08

STEP 8 OF 11 · EXPERIMENT

Add wind speed.

  1. Add ,wind_speed_10m to the end of the current= part.
  2. Inside try, add the two wind lines after the unit line.
  3. Replace the old status.textContent line with the new one.

script.js · two changes

// in weatherUrl
  "&current=temperature_2m,wind_speed_10m";

// inside try: add after the unit line
const wind = data.current.wind_speed_10m;
const windUnit = data.current_units.wind_speed_10m;
// replace the old status line with:
status.textContent =
  `Nairobi: ${temp} ${unit}, wind ${wind} ${windUnit}`;

✅ Check: something like Nairobi: 21.4 °C, wind 12.3 km/h.

09

STUCK? · COMMON FIXES

Check the Console.

  • “Weather is unavailable”Check your internet, then compare the address with Step 3 letter by letter.
  • Stuck on “Loading…”Open the Console tab and read the first red error.
  • “undefined” on the pageA name is misspelled, such as temperature_2m or current_units.
  • “await is only valid…”Put async before function loadWeather().

Open the API address in a tab again. If it shows JSON, the API works and the bug is in your code.

10

STEP 9 OF 11 · YOUR CAPSTONE

Add loading, empty and error states.

  1. Open your capstone in NitroIDE. Download ZIP first as a backup.
  2. Weather Dashboard: use your loadWeather code for each town you chose.
  3. Opportunities Hub / CyberSmart Quest: wrap your data in a load function like this. Keep your array for now.
  4. Call the function at the bottom of script.js.

script.js · pattern to copy and change

async function loadOpportunities() {
  status.textContent = "Loading…";
  try {
    const data = opportunities; // Lesson 7: use fetch
    if (data.length === 0) {
      status.textContent = "No opportunities yet.";
      return;
    }
    showResults(data);
  } catch (error) {
    status.textContent = "Could not load opportunities.";
    console.error(error);
  }
}

loadOpportunities();

✅ Check: your page shows “Loading…”, then data, or a clear empty or error message. Never a blank screen.

11

STEP 10 OF 11 · SAFE API USE

Keep secrets out.

  1. Use APIs that need no key, like Open-Meteo.
  2. Never type a password, API key or token into your code.
  3. Request only the data your page shows.
  4. If a site asks for payment details, stop and choose a different API.

✅ Check: your script.js contains no keys, passwords or private details.

12

STEP 11 OF 11 · SAVE + PREPARE

Save it. Get ready for Git.

  1. Click Download ZIP on your capstone and keep a copy.
  2. In your journal, draw: your page → request → API → JSON response → your page.
  3. Write one sentence each: what await does, and what catch does.
  4. Before Lesson 7, ask for permission to make a GitHub account and to install VS Code (code.visualstudio.com).

✅ Check: your capstone shows data with loading and error states, and your journal is done.

Next: Lesson 7 — Git, GitHub and VS Code →

13
01/13

← → to navigate · F fullscreen

Slide 1 of 13