CodingNic

Weather API & Current Conditions

Build the Current Weather Request

Weather API & Current Conditions 30 min read

Build the Current Weather Request

Build the Current Weather Request

Task

Create fetchWeather(city) so the app can request current conditions from the /weather endpoint.

Open

Add fetchWeather() below the helper functions in script.js.

Implementation

javascript
async function fetchWeather(city) {
  requireKey();
  showError("");
  showLoader(true);

  try {
    const params = new URLSearchParams({
      q: city,
      appid: API_KEY,
      units: state.unit
    });

    const response = await fetch(`${API_BASE}/weather?${params}`);

    if (!response.ok) {
      if (response.status === 404) {
        throw new Error("City not found. Check the spelling and try again.");
      }
      if (response.status === 401) {
        throw new Error("Invalid API key. Check script.js.");
      }
      throw new Error("Weather service is unavailable right now.");
    }

    const current = await response.json();
    console.log(current);
  } catch (error) {
    showError(error.message);
  } finally {
    showLoader(false);
  }
}

URLSearchParams creates the query string from the city, key, and selected unit. fetch() returns a Response; response.ok prevents failed HTTP responses from being treated as weather data. response.json() converts the response body into the JavaScript object used by later renderers.

Test

Temporarily call fetchWeather("New York") from the bottom of the file. Open DevTools and inspect the logged object. Confirm it contains name, main, weather, wind, coord, and timezone. Remove the temporary call.

Expected result

The app can retrieve and parse a real current-weather response.

Checkpoint

Before moving on, confirm the expected result in the running app and make sure the browser console has no blocking errors.