APIs unlock a world of live data. What better way to practice API consumption than by building a real-time weather app using JavaScript and the OpenWeatherMap API?
In this post, weβll walk through creating a weather app that:
- Takes user input (a city name)
- Fetches weather data using the OpenWeatherMap API
- Displays temperature, weather conditions, and icons
- Handles errors gracefully
What You’ll Learn
- Fetching data from an API with fetch()
- Handling API responses and JSON
- Basic DOM manipulation
- Displaying dynamic content
- Simple error handling
Step 1: Get Your API Key
- Go to https://openweathermap.org/api
- Sign up and create an API key (usually takes a few minutes)
π File Structure:
weather-app/
βββ index.html
βββ styles.css
βββ script.js
Step 2: Create the HTML
<!-- index.html -->
<!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="weather-container">
<h1>π€ Weather App</h1>
<input type="text" id="cityInput" placeholder="Enter city name" />
<button id="searchBtn">Search</button>
<div id="weatherResult" class="result"></div>
</div>
<script src="script.js"></script>
</body>
</html>
π¨ Step 3: Add Some CSS
/* styles.css */
body {
font-family: Arial, sans-serif;
background: linear-gradient(to right, #74ebd5, #acb6e5);
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.weather-container {
text-align: center;
background: white;
padding: 2rem;
border-radius: 10px;
box-shadow: 0 4px 10px rgba(0,0,0,0.2);
}
input {
padding: 0.5rem;
margin-right: 0.5rem;
}
.result {
margin-top: 1rem;
font-size: 1.2rem;
}
π Step 4: Write the JavaScript
// script.js
const apiKey = 'YOUR_API_KEY_HERE'; // Replace with your OpenWeatherMap API key
document.getElementById('searchBtn').addEventListener('click', async () => {
const city = document.getElementById('cityInput').value.trim();
const resultDiv = document.getElementById('weatherResult');
if (!city) {
resultDiv.textContent = 'Please enter a city name.';
return;
}
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
try {
resultDiv.textContent = 'Loading...';
const response = await fetch(url);
if (!response.ok) throw new Error('City not found');
const data = await response.json();
const { name, main, weather } = data;
resultDiv.innerHTML = `
<h2>${name}</h2>
<p>π‘ Temperature: ${main.temp}Β°C</p>
<p>βοΈ Condition: ${weather[0].description}</p>
<img src="https://openweathermap.org/img/wn/${weather[0].icon}@2x.png" alt="${weather[0].description}">
`;
} catch (error) {
resultDiv.textContent = error.message;
}
});
You now have a working real-time weather app that:
Take user input, Fetches weather data from API, and displays Temperature with a simple UI.
You may also like this: