Want to display real-time weather information on your website? With the OpenWeather API and a little JavaScript, you can show the temperature, weather condition, and more — personalized for any city.
In this tutorial, you’ll learn how to fetch and display weather data using OpenWeather’s free API in a beginner-friendly way.
☁️ What You’ll Learn
- How to get an API key from OpenWeather
- How to make an API request using JavaScript
- How to display the weather info on the screen
- How to handle errors and improve the UX
🧾 Step 1: Get Your API Key
- Go to https://openweathermap.org/api
- Sign up for a free account
- Copy your API key (usually a long alphanumeric string)
You’ll need this key to make requests.
🧱 Step 2: HTML Structure
<div class="weather">
<h2>Weather Info</h2>
<input type="text" id="cityInput" placeholder="Enter city name" />
<button onclick="getWeather()">Get Weather</button>
<div id="result"></div>
</div>
🎨 Step 3: Basic CSS Styling (Optional)
.weather {
font-family: Arial, sans-serif;
text-align: center;
padding: 2rem;
}
input, button {
padding: 10px;
margin: 10px;
}
⚙️ Step 4: JavaScript to Fetch Weather Data
async function getWeather() {
const city = document.getElementById("cityInput").value;
const apiKey = "YOUR_API_KEY_HERE"; // Replace with your OpenWeather API key
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
try {
const response = await fetch(url);
if (!response.ok) throw new Error("City not found");
const data = await response.json();
const temp = data.main.temp;
const condition = data.weather[0].description;
document.getElementById("result").innerHTML = `
<h3>${data.name}</h3>
<p>🌡️ Temperature: ${temp} °C</p>
<p>🌥️ Condition: ${condition}</p>
`;
} catch (error) {
document.getElementById("result").innerHTML = `<p>${error.message}</p>`;
}
}
✅ How It Works
- The
fetch()
function requests weather data for the entered city. - The URL includes the city name, API key, and sets units to metric.
- If successful, it shows the temperature and weather description.
- If the city is not found, it shows an error.
🧠 Bonus Tips
- Use
navigator.geolocation
to detect the user’s location automatically. - Customize the UI with icons or images based on
data.weather[0].icon
. - Cache results in
localStorage
to avoid multiple API requests.
✅ Final Result
You’ve just built a working weather app using:
- ✅ JavaScript and
fetch()
- ✅ A real API (OpenWeather)
- ✅ Dynamic user input
- ✅ Error handling for UX
Perfect project to practice APIs and DOM manipulation!