Weather App with API in JS. 10 Days 10 Beginner JS Projects. Day 6

Weather App with API in JS. 10 Days 10 Beginner JS Projects. Day 6

You’ve learned HTML and CSS and started to learn JavaScript. You studied all the basics. Now it is time to practice.

But... What should I build?

We'll build 10 projects in 10 days. We'll be exploring 10 beginner-friendly JavaScript projects one by one that will help you sharpen your skills and get you started on your journey to becoming a skilled web developer. These projects are easy to follow and require minimal experience, making them perfect for beginners. Let's get started and dive into the exciting world of JavaScript projects! We'll focus on JavaScript so I won't explain every HTML and CSS code. You can style it however you want and add things to make your own.

Let's go.

What we will build in 10 days:

  1. Simple Calculator

  2. Random Quote Generator

  3. To-do List

  4. Image Slider

  5. Stopwatch

  6. Weather App with an API

  7. Random Number Guessing Game

  8. Rock-Paper-Scissors

  9. Memory Game

  10. Countdown Timer.

Day 6.

Weather App with an 'OpenWeatherMap' API.

Today, we'll build a simple weather app with an API to search for city names and learn the city's weather. We'll use an API today. It's a great project to practice your API knowledge.

First of all. What is an API?

API stands for Application Programming Interface, which is just a fancy way of saying that it's a tool that allows different software applications to talk to each other. Think of it like a waiter at a restaurant - the waiter acts as the intermediary between the customer and the kitchen. The customer tells the waiter what they want, and the waiter goes back to the kitchen to communicate the order and get the food.

In the same way, an API acts as a middleman between two different software applications. For example, a weather app we will build today. That weather app probably gets its information from a different source, like a weather API. When you open the app, it sends a request to the weather API asking for the current weather conditions in your area. The weather API then returns the information to the app, which displays it to you.

APIs are like a shared language that allows different applications to communicate with each other and share information. They're used in all sorts of industries, from social media to finance to healthcare.

Let's start.

Simple HTML to display the input, button, and weather information.

<h1>Weather App</h1>
    <label for="city">City:</label>
    <input type="text" id="city" name="city">
    <button onclick="getWeather()">Get Weather</button>
    <div id="weather"></div>

Simple CSS:

body {
    font-family: Arial, sans-serif;
    background-color: #f2f2f2;
  display:flex;
  flex-direction:column;
  align-items:center;
  gap:.3rem;
  font-size:1.5rem;
}

h1 {
    text-align: center;
}

label {
    display: block;
    margin-top: 10px;
}

input {
    padding: 5px;
    border: none;
    border-radius: 5px;
    margin-bottom: 10px;
  text-transform:capitalize;
  width:20vw;
}

button {
    padding: 5px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

#weather {
    margin-top: 20px;
    padding: 10px;
    background-color: #fff;
    border-radius: 5px;
    display: none;
}

And JS:

const apiKey = "Your_API_Key";

Go to the OpenWeatherMap website, and sign up. After signing up, go to the API section. Grab your API key, and paste it here.

An API key is a unique code or identifier that is assigned to a user or application that is accessing an API. It acts like a password or a secret key that is required to authenticate and authorize access to the API.

function getWeather() {
    const city = document.getElementById("city").value;
}

The first line declares a function named getWeather. This function will be executed when the user enters a city name in the input field and clicks the search button.

The second line retrieves the value of the input field with the id of city and assigns it to a constant variable named city. This variable will be used later in the function to construct the API URL.

fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`)

This line makes a fetch request to the OpenWeatherMap API, which returns a promise that resolves to the API response. The URL of the API request includes the city name and the API key that was declared earlier. The template literals (``) used in the URL allow for the dynamic inclusion of the city and apiKey variables.

Learn more about fetch requests.

.then(response => response.json())

This line uses the arrow function syntax (=>) to define a callback function that converts the response from the API to a JavaScript object. The .json() method is called on the response object, which returns a promise that resolves to the parsed JSON data.

.then(data => {

This line defines another arrow function that handles the parsed JSON data from the previous .then() method.

To see the data, write console.log(data) and inspect the web browser. You will see the JSON file of the data(name, long, lat, etc.).

const weather = document.getElementById("weather");

This line retrieves an HTML element with the id of weather and assigns it to a constant variable named weather. This element will be used later in the function to display the weather data.

weather.innerHTML = `
    <p>Weather in ${data.name}: ${data.weather[0].description}</p>
    <p>Temperature: ${Math.round(data.main.temp - 273.15)} &deg;C</p>
    <p>Humidity: ${data.main.humidity}%</p>
    <p>Wind Speed: ${data.wind.speed} m/s</p>
`;

This block of code uses template literals to dynamically create an HTML string that displays the weather data returned by the API. The data variable is an object that contains various weather-related properties. These properties are accessed using dot notation, and the values are interpolated into the HTML string using the ${} syntax.

weather.style.display = "block";

This line sets the display property of the weather element to "block", which makes the element visible on the page.

})
.catch(error => console.log(error));

This block of code defines an error handler using the .catch() method, which logs any errors that occur during the execution of the fetch request to the console. This is a useful way to diagnose and troubleshoot errors that may occur during API requests.

Full JS code.

const apiKey = "Your_API_Key";

function getWeather() {
    const city = document.getElementById("city").value;

    fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`)
        .then(response => response.json())
        .then(data => {
            const weather = document.getElementById("weather");
            weather.innerHTML = `
                <p>Weather in ${data.name}: ${data.weather[0].description}</p>
                <p>Temperature: ${Math.round(data.main.temp - 273.15)} &deg;C</p>
                <p>Humidity: ${data.main.humidity}%</p>
                <p>Wind Speed: ${data.wind.speed} m/s</p>
            `;
            weather.style.display = "block";
        })
        .catch(error => console.log(error));
}

That's it for today. Hope you like it.

See you tomorrow.

Here is the GitHub code.