Projects

Building a Weather App with API

Introduction to the Weather App with API

Welcome to the beginner-friendly tutorial on building a Weather App with API! In this project, we'll create a weather app that fetches real-time weather data from an API and displays it on your webpage. This project is an excellent way to learn how to work with APIs, handle async functions, and display data on your webpage.

Setting Up Your Workspace

Creating Your Project Folder and Files

Before we begin coding, let's set up a workspace for our project. This folder will be your digital canvas, where you'll keep all the project files organized.

Step 1: Create Your Project Folder

Create a new folder on your computer to store all your project files. You can name it "weather-app".

On Windows:
  1. Right-click on your desktop.
  2. Choose "New" > "Folder".
  3. Name it "weather-app".
On Mac:
  1. Right-click on your desktop.
  2. Choose "New Folder".
  3. Name it "weather-app".

Step 2: Get Your Text Editor Ready

You'll need a text editor to write your code. We recommend Visual Studio Code, which is free and beginner-friendly.

  1. Download Visual Studio Code from code.visualstudio.com.
  2. Install it on your computer.
  3. Open VS Code and drag your "weather-app" folder into the window.

Step 3: Create Your Project Files

We need three essential files for our project:

To create these files:

  1. Open VS Code.
  2. index.html - Click "New File" and save it as "index.html".
  3. styles.css - Click "New File" again and save it as "styles.css".
  4. script.js - Click "New File" once more and save it as "script.js".

🎯 Success Check: You should now have:

👉 Tip: If something's not working, try restarting VS Code or creating the files using the "File → New File" menu.

Setting Up the HTML Structure

Creating the Weather App HTML

Let's start by building the HTML structure for our weather app. HTML is like the foundation of our app.

  1. 1. Open "index.html": Open your "index.html" file in your code editor.
  2. 2. Add the Weather App HTML: Copy and paste the following code into your "index.html" file:
    <!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>
      <link rel="stylesheet" href="styles.css">
    </head>
    <body>
      <div class="container">
        <h1>Weather App</h1>
        <form id="city-form">
          <input type="text" id="city-input" placeholder="Enter a city" required>
          <button type="submit">Get Weather</button>
        </form>
        <div id="weather-container" class="hide">
          <h2 id="city"></h2>
          <p id="temperature"></p>
          <p id="description"></p>
        </div>
      </div>
      <script src="script.js"></script>
    </body>
    </html>

Let's break down the HTML structure:

Save your "index.html" file. Now we have the basic HTML structure in place. In the next step, we'll add some styling to make it look nice!

Styling the Weather App

Adding CSS Styles

CSS is like the paint and brushes we use to make our app visually appealing. Let's add some styles to our weather app.

  1. 1. Open "styles.css": Open the "styles.css" file in your code editor.
  2. 2. Add Weather App Styles: Copy and paste the following CSS code into your "styles.css" file:
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      background-color: #f4f4f4;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }
    
    .container {
      background-color: #fff;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      width: 400px;
      text-align: center;
    }
    
    h1 {
      margin: 0 0 20px;
      font-size: 1.5rem;
    }
    
    form {
      margin-bottom: 20px;
    }
    
    input[type="text"] {
      width: 100%;
      padding: 10px;
      margin-bottom: 10px;
      border: 1px solid #ddd;
      border-radius: 5px;
      font-size: 1rem;
    }
    
    button {
      background-color: #007bff;
      color: #fff;
      border: none;
      padding: 10px 20px;
      border-radius: 5px;
      cursor: pointer;
      font-size: 1rem;
      transition: background-color 0.3s ease;
    }
    
    button:hover {
      background-color: #0056b3;
    }
    
    #weather-container {
      text-align: left;
    }
    
    #weather-container h2, #weather-container p {
      margin: 10px 0;
    }
    
    .hide {
      display: none;
    }

Let's understand the CSS rules we just added:

Save your "styles.css" file. Now, if you open "index.html" in a web browser, you'll see the styled weather app.

Getting an API Key from OpenWeatherMap

Before we can fetch weather data, we need to get an API key from OpenWeatherMap. Follow these steps to get your API key:

  1. 1. Sign Up for OpenWeatherMap: Go to the OpenWeatherMap website and sign up for a free account.
  2. 2. Get Your API Key: Once you're logged in, go to the "API keys" section in your account dashboard. You should see a default API key. If not, generate a new one by clicking the "Generate" button.
  3. 3. Save Your API Key: Copy and save your API key somewhere safe. You'll need it to make API requests.

Note: Keep your API key secure and do not share it publicly.

Adding JavaScript for User Interactions

Handling Form Submission

Now, let's add JavaScript to make our app interactive! We'll start by handling form submission and fetching weather data from the API.

Selecting HTML Elements

First, we need to select the HTML elements we want to work with. We'll select the form, input field, and weather container.

  1. 1. Open "script.js": Open the "script.js" file in your code editor.
  2. 2. Selecting Elements: Copy and paste the following JavaScript code into your "script.js" file:
    // Selecting HTML elements
    const cityForm = document.getElementById('city-form');
    const cityInput = document.getElementById('city-input');
    const weatherContainer = document.getElementById('weather-container');
    const cityElement = document.getElementById('city');
    const temperatureElement = document.getElementById('temperature');
    const descriptionElement = document.getElementById('description');

Here, we're using the getElementById method to select the HTML elements with specific IDs.

Handling Form Submission

Next, we'll add an event listener to the form to handle the submit event. We'll prevent the default form submission behavior and call a function to fetch the weather data.

  1. 3. Handling Form Submission: Copy and paste the following JavaScript code into your "script.js" file:
    // Handling form submission
    cityForm.addEventListener('submit', (e) => {
      e.preventDefault();
      const city = cityInput.value.trim();
      if (city) {
        fetchWeatherData(city);
        cityInput.value = '';
      } else {
        alert('Please enter a city name.');
      }
    });

In this part, we're using the addEventListener method to listen for the 'submit' event on the form. We prevent the default form submission behavior using e.preventDefault(), trim the city input, and call the fetchWeatherData function if the city is not empty. If the city is empty, we show an alert.

Fetching Weather Data from the API

Now, let's create the fetchWeatherData function to fetch weather data from the API.

  1. 4. Fetching Weather Data: Copy and paste the following JavaScript code into your "script.js" file:
    // Function to fetch weather data
    async function fetchWeatherData(city) {
      const apiKey = 'YOUR_API_KEY'; // Replace with your API key
      const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`;
    
      try {
        const response = await fetch(apiUrl);
        if (response.ok) {
          const data = await response.json();
          displayWeatherData(data);
        } else {
          throw new Error('City not found');
        }
      } catch (error) {
        alert(error.message);
      }
    }

In this function, we use the fetch function to make an API request to the OpenWeatherMap API. We use async/await to handle the asynchronous request. If the response is successful, we parse the JSON data and call the displayWeatherData function to display the weather data. If the response is not successful, we throw an error and show an alert.

Displaying Weather Data

Now, let's create the displayWeatherData function to display the weather data on the webpage.

  1. 5. Displaying Weather Data: Copy and paste the following JavaScript code into your "script.js" file:
    // Function to display weather data
    function displayWeatherData(data) {
      const { name, main, weather } = data;
    
      cityElement.innerText = name;
      temperatureElement.innerText = `Temperature: ${main.temp}°C`;
      descriptionElement.innerText = `Description: ${weather[0].description}`;
      weatherContainer.classList.remove('hide');
    }

In this function, we extract the necessary data from the API response and update the corresponding HTML elements. We also remove the hideclass from the weather container to display the weather data.

Making the Weather App Responsive

Making the Weather App Responsive

Let's ensure our weather app looks great on various devices by adding responsive design using CSS media queries.

  1. 1. Open "styles.css": Open the "styles.css" file in your code editor.
  2. 2. Add Responsive Design Styles: Copy and paste the following CSS code into your "styles.css" file:
    @media (max-width: 600px) {
      .container {
        width: 90%;
      }
    
      input[type="text"] {
        font-size: 0.9rem;
      }
    
      button {
        padding: 8px 16px;
        font-size: 0.9rem;
      }
    
      #weather-container h2, #weather-container p {
        font-size: 0.9rem;
      }
    }

Let's understand the CSS rules we just added:

Save your "styles.css" file. Now, if you resize your browser window or view the weather app on different devices, you'll see the layout adapt to different screen sizes.

Final Thoughts

Congratulations! You've completed the Weather App with API project. You've learned how to create a weather app that fetches real-time weather data from an API and displays it on your webpage. This project introduced you to working with APIs, handling async functions, and displaying data on your webpage.

Feel free to customize and expand your weather app further. You can add more features, improve the design, or even create a mobile version. Happy coding and exploring the world of web development! 🚀