Build a Weather App with Fetch API – JavaScript (a.k.a. Your Personal Meteorologist)

 

Ever wanted to build a simple yet powerful weather app using JavaScript? Well, today’s your lucky day! With the Fetch API, we can grab real-time weather data from an API and display it in our web app without breaking a sweat. (Unlike the weather, which might make you sweat.) 

In this tutorial, we’ll create a weather application that fetches live data, so you can finally impress your friends with your coding AND weather prediction skills.

What is the Fetch API?

The Fetch API is a modern way to make HTTP requests in JavaScript. It allows you to retrieve data from external sources, such as a weather API, without needing jQuery or XMLHttpRequest (because, let’s be real, no one wants to deal with XMLHttpRequest anymore).

Basic Fetch Syntax

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Oops! Something went wrong:', error));

Easy, right? Now let’s use this to get some real-time weather data!

Step-by-Step Guide: Building the Weather App

1. Get an API Key from OpenWeatherMap

First, sign up at OpenWeatherMap and get a free API key. This will let us fetch weather data.

2. Create the Basic HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather App</title>
</head>
<body>
    <h1>Weather App</h1>
    <input type="text" id="city" placeholder="Enter city name...">
    <button onclick="getWeather()">Get Weather</button>
    <div id="weatherInfo"></div>
    <script src="script.js"></script>
</body>
</html>

3. Write the JavaScript (script.js)

const apiKey = 'YOUR_API_KEY';

function getWeather() {
    const city = document.getElementById('city').value;
    if (!city) return alert('Please enter a city!');

    fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`)
        .then(response => response.json())
        .then(data => {
            document.getElementById('weatherInfo').innerHTML = `
                <h2>${data.name}, ${data.sys.country}</h2>
                <p>Temperature: ${data.main.temp}°C</p>
                <p>Weather: ${data.weather[0].description}</p>
            `;
        })
        .catch(error => console.error('Error fetching weather:', error));
}

4. Try It Out!

Open the HTML file in your browser, enter a city name, and boom! Your weather data appears instantly.

Bonus: Improve Your Weather App

Style it with CSS – Make it look awesome!  Add error handling – Show a message if the city is not found.  Use Geolocation API – Detect the user’s location automatically. Display weather icons – Use OpenWeatherMap icons for extra coolness. 

Conclusion

With just a few lines of JavaScript and the Fetch API, you’ve built your own weather app!  Now you can check the weather without even opening another tab. (Take that, weather websites!)

Happy coding!

 

Post a Comment

0 Comments