Back to Blog
Lesson 39 of the JavaScript: From Zero to Interactive Web Pages course
August 26, 20264 min read

Building the Weather Service: Fetching and Extracting Data

Learn how to build a robust weather service by configuring API URLs, performing fetch requests, and extracting temperature and conditions for your dashboard.

Weather monitoring equipment with a sunset sky backdrop, highlighting technology and atmosphere.

Previously in this course, we covered Mastering the Fetch API: GET Requests and JSON Data in JavaScript and Working with JSON Data: A Guide to Parsing and Traversal. In this lesson, we are shifting from generic requests to a specific, production-ready goal: building a dedicated weather service module for our dashboard project.

Why You Need a Weather Service Layer

When you start building features that rely on external data, you will quickly realize that scattering fetch() calls throughout your codebase makes it impossible to debug. If the API URL changes or you need to add an authentication key, you don't want to hunt through five different files to update it.

A "Service" is simply a function (or set of functions) that acts as the single source of truth for your application's communication with a specific external resource.

Configuring Your API Request

For this exercise, we will use the OpenWeatherMap API structure as our model. Every weather API requires a specific URL construction that includes your API key and the target location.

First, we define our base configuration. We want to avoid hardcoding strings directly inside our fetch logic.

JAVASCRIPT
const CONFIG = {
  baseUrl: "https://api.openweathermap.org/data/2.5/weather",
  apiKey: "YOUR_API_KEY_HERE" // In a real app, never expose this in plain JS
};

Writing the Weather Fetch Function

Now, we create a function that accepts a city name and builds the request. We use template literals to inject the parameters into the URL string.

JAVASCRIPT
async function fetchWeatherData(city) {
  const url = CE9178">`${CONFIG.baseUrl}?q=${city}&appid=${CONFIG.apiKey}&units=metric`;

  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error("City not found");
    }
    const data = await response.json();
    return extractWeatherInfo(data);
  } catch (error) {
    console.error("Weather fetch failed:", error);
  }
}

Data Extraction Strategy

The API response is usually a large, deeply nested object. You rarely need every single piece of information. The extractWeatherInfo helper function allows us to "clean" the data before it ever reaches our UI logic.

JAVASCRIPT
function extractWeatherInfo(data) {
  return {
    temp: data.main.temp,
    condition: data.weather[0].main,
    humidity: data.main.humidity,
    city: data.name
  };
}

// Usage:
fetchWeatherData("London").then(weather => {
  console.log(CE9178">`It is ${weather.temp}°C and ${weather.condition} in ${weather.city}.`);
});

Hands-on Exercise

  1. Define the Service: Create a new file named weatherService.js.
  2. Implement: Write a function that takes a city name as an argument and returns the specific temperature and main weather condition as an object.
  3. Log the Output: Use your function to fetch data for "Tokyo" and console.log the resulting object to verify your extraction logic works.

Common Pitfalls

  • Case Sensitivity: Most APIs are picky about city names. Always use .trim() and be aware that "london" and "London" might return different results depending on the provider.
  • API Key Exposure: Never commit your API keys to public repositories like GitHub. Use environment variables (which we will touch on later in the course) to keep these secret.
  • Ignoring Errors: Beginners often forget that fetch() only rejects on network failures. If the server returns a 404 (City Not Found), fetch succeeds. Always check response.ok as shown in the example above.

Frequently Asked Questions

Q: Why separate the fetch logic from the data extraction logic? A: It keeps your code maintainable. If the API changes the structure of their JSON response, you only have to update the extractWeatherInfo function, rather than every place in your app where you display weather.

Q: Can I fetch multiple cities at once? A: Most free-tier weather APIs limit you to one location per request. You would need to call your function in a loop, but be careful not to trigger "Rate Limiting" (the API blocking you for too many requests).

Q: How do I handle units like Fahrenheit vs Celsius? A: Most APIs include a units parameter (e.g., &units=metric for Celsius or &units=imperial for Fahrenheit). Always set this in your configuration object.

Recap

We have successfully decoupled our data fetching from our UI logic. By creating a dedicated fetchWeatherData function and an extractWeatherInfo helper, we have built a stable, reusable service layer. This modular approach is the hallmark of professional frontend development and ensures your dashboard remains easy to update as requirements grow.

Up next: We will take this data and render it dynamically into our dashboard UI.

Similar Posts