Skip to Content
Course content

186: Building a Basic Weather Widget Using an API

Click on the "Edit" button in the top corner of the screen to edit your slide content.

How do I actually call the weather API and get the data?

When you're building a widget, you aren't storing the weather data yourself—you're asking a server for it. Most modern APIs use JSON, and the cleanest way to handle this in JavaScript is with async and await. I've found that using .then() chains can get messy quickly, especially when you start nesting calls.

Here is how I usually structure a basic fetch call for something like OpenWeatherMap. Notice how I wrap it in an async function so I can use await to pause the execution until the data actually arrives.

async function getWeather(city) {
  const apiKey = 'YOUR_API_KEY_HERE';
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;

  try {
    const response = await fetch(url);
    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Something went wrong with the network request:", error);
  }
}

The API returns a huge object—how do I extract just the temperature and city name?

If you console.log the response from a weather API, it looks like a mountain of data. You don't need all of it. To make a widget, you just need to "drill down" into the object. For instance, OpenWeatherMap nests the temperature inside a main object and the weather description inside an array called weather.

I like to destructure these values immediately to keep the code readable. Instead of writing data.main.temp everywhere, do this:

async function updateWidget() {
  const data = await getWeather('London');
  
  // Destructuring the nested properties we actually care about
  const { name, main: { temp }, weather } = data;
  const description = weather[0].description;

  document.getElementById('city-name').innerText = name;
  document.getElementById('temp-display').innerText = `${Math.round(temp)}°C`;
  document.getElementById('status').innerText = description;
}

What's the best way to handle it when a user enters a city that doesn't exist?

This is where a lot of developers trip up. fetch only throws an error (triggering the catch block) if there is a network failure—like your internet going out. If the API returns a 404 Not Found because the user typed "FakeCity123", fetch actually considers that a "successful" response.

You have to manually check if the response was okay. I always check the response.ok property before I even try to parse the JSON. If it's false, I throw an error myself to jump straight to the catch block where I can tell the user what happened.

async function getWeather(city) {
  const apiKey = 'YOUR_API_KEY_HERE';
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;

  try {
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new Error('City not found. Please try again!');
    }

    return await response.json();
  } catch (error) {
    // Now this handles both network crashes AND 404s
    document.getElementById('error-message').innerText = error.message;
  }
}



📋 Practical Task

Build a Dynamic Weather Search Toggle

Create a small weather widget interface. It should include an input field for a city name, a search button, and a display area for the results. Using a free API (like OpenWeatherMap), write a JavaScript function that:

  • Triggers the API call only when the search button is clicked.
  • Updates the DOM to show the city name, current temperature, and a brief weather description.
  • Displays a specific error message in red text if the API returns a 404 (City not found).
  • Uses Math.round() to ensure the temperature is displayed as a whole number.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.