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.
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.
Create a new folder on your computer to store all your project files. You can name it "weather-app".
On Windows:You'll need a text editor to write your code. We recommend Visual Studio Code, which is free and beginner-friendly.
We need three essential files for our project:
To create these files:
🎯 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.
Let's start by building the HTML structure for our weather app. HTML is like the foundation of our app.
<!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:
<div class="container">
: The main container for our app.<h1>Weather App</h1>
: The title of our app.<form id="city-form">
: The form for entering a city.<input type="text" id="city-input" placeholder="Enter a city" required>
: The input field for the city name.<button type="submit">Get Weather</button>
: The button to fetch the weather data.<div id="weather-container" class="hide">
: The container for displaying the weather data.<h2 id="city"></h2>
: The element for displaying the city name.<p id="temperature"></p>
: The element for displaying the temperature.<p id="description"></p>
: The element for displaying the weather description.<script src="script.js"></script>
: Includes the JavaScript file for handling the app's functionality.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!
CSS is like the paint and brushes we use to make our app visually appealing. Let's add some styles to our weather app.
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:
body
: Sets the default font, removes margins and padding, and centers the content on the screen..container
: Styles the container with a white background, padding, rounded corners, and a shadow.h1
: Styles the title with a larger font size and margin.form
: Adds margin to the form.input[type="text"]
: Styles the input field with a fixed width, padding, border, and font size.button
: Styles the button with a blue background, white text, no border, padding, border-radius, cursor, and transition for smooth changes.#weather-container
: Styles the weather container with text alignment.#weather-container h2, #weather-container p
: Adds margin to the city name, temperature, and description..hide
: Hides elements that should not be visible initially.Save your "styles.css" file. Now, if you open "index.html" in a web browser, you'll see the styled weather app.
Before we can fetch weather data, we need to get an API key from OpenWeatherMap. Follow these steps to get your API key:
Note: Keep your API key secure and do not share it publicly.
Now, let's add JavaScript to make our app interactive! We'll start by handling form submission and fetching weather data from the API.
First, we need to select the HTML elements we want to work with. We'll select the form, input field, and weather container.
// 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.
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.
// 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.
Now, let's create the fetchWeatherData
function to fetch weather data from the API.
// 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.
Now, let's create the displayWeatherData
function to display the weather data on the webpage.
// 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 hide
class from the weather container to display the weather data.
Let's ensure our weather app looks great on various devices by adding responsive design using CSS media queries.
@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:
@media (max-width: 600px)
: A media query for screens up to 600px wide (e.g., mobile phones)..container
: Adjusts the width of the container to 90% for better visibility on smaller screens.input[type="text"]
: Adjusts the font size of the input field for better readability on smaller screens.button
: Adjusts the padding and font size of the button for better readability on smaller screens.#weather-container h2, #weather-container p
: Adjusts the font size of the city name, temperature, and description for better readability on smaller screens.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.
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! 🚀