Project 2:
Weather App using API



Overview

This project will help you build a Weather App using pure JavaScript and an external API. We will use the OpenWeatherMap API to fetch real-time weather data based on the user's city input.

What You'll Learn

Step 1: Get API Access

Sign up at OpenWeatherMap and get your free API key.

Step 2: Understand the API Request

The API URL to get weather for a city looks like this:


https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY&units=metric
    

Question:

What are the parameters in the API URL?

Answer: q is the city name, appid is your API key, and units=metric ensures temperature is in Celsius.

Step 3: Write JavaScript Code (Browser Console)

This version runs directly in the browser console. Replace YOUR_API_KEY with your actual key.


const city = "Delhi";
const apiKey = "YOUR_API_KEY"; // Replace with your real API key

fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`)
  .then(response => {
    if (!response.ok) {
      throw new Error("City not found");
    }
    return response.json();
  })
  .then(data => {
    console.log(`Weather in ${data.name}:`);
    console.log(`Temperature: ${data.main.temp}°C`);
    console.log(`Weather: ${data.weather[0].description}`);
    console.log(`Humidity: ${data.main.humidity}%`);
    console.log(`Wind Speed: ${data.wind.speed} m/s`);
  })
  .catch(error => {
    console.error("Error fetching weather data:", error.message);
  });
    

Output:

Weather in Delhi:
Temperature: 32°C
Weather: clear sky
Humidity: 28%
Wind Speed: 3.6 m/s
    

Code Description

Question:

What happens if the user enters an invalid city name?

Answer: The API returns a 404 status, and our code throws an error with the message "City not found".

Step 4: Run in Node.js (with Readline)

This version lets users enter city names via command line:


// weather.js
const readline = require("readline");
const https = require("https");

const apiKey = "YOUR_API_KEY"; // Replace with your key

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question("Enter a city name: ", function(city) {
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;

  https.get(url, (res) => {
    let data = "";
    
    res.on("data", chunk => data += chunk);
    res.on("end", () => {
      const weather = JSON.parse(data);
      if (weather.cod !== 200) {
        console.error("Error:", weather.message);
      } else {
        console.log(`Weather in ${weather.name}:`);
        console.log(`Temperature: ${weather.main.temp}°C`);
        console.log(`Condition: ${weather.weather[0].description}`);
      }
      rl.close();
    });
  }).on("error", (e) => {
    console.error("Failed to fetch:", e.message);
    rl.close();
  });
});
    

Output:

Enter a city name: Paris
Weather in Paris:
Temperature: 21°C
Condition: few clouds
    

Best Practices

Wrap-up

This project helped you connect JavaScript to a real-world weather API. You now know how to fetch, parse, and display data dynamically using modern JavaScript techniques.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M