How to Build a Simple Weather App with a REST API in 15 Minutes
Fetching data from a third-party API is a fundamental skill for any developer. A Weather API is the perfect project to start with: it’s fun, practical, and demonstrates the core concepts of making HTTP requests, handling JSON data, and dynamically updating a UI.
This tutorial will walk you through the entire process of building a simple but functional web-based weather app. We'll use HTML, CSS, and vanilla JavaScript to call a powerful and easy-to-use REST API. By the end, you'll have a working component that can get the live weather for any city in the world.
Step 1: Get Your Free API Key
Before you write a single line of code, you need to be able to authenticate your requests.
- Navigate to
juheapi.com
and sign up for a free account. - Go to your user dashboard or control panel to find your API keys.
- Generate a new API key for this project and copy it somewhere safe. This key is your passport to accessing the API.
Step 2: Anatomy of the Weather API Call
Understanding the API's structure is key. Luckily, this one is very straightforward.
-
The Endpoint: All our requests will go to the following URL:
https://hub.juheapi.com/weather/v1/
-
Request Parameters: You can query the API in several ways, but the most common is by city name. The request will look like this:
https://hub.juheapi.com/weather/v1/city?apikey=value&q=value
-
The JSON Response: A successful request will return a clean JSON object. Let's look at the most useful fields:
{ "name": "London", "weather": "Clouds", "weather_description": "overcast clouds", "temp": "14.5", "humidity": "82%", "pressure": "1012 hPa", "sunrise": "1661834147", // UNIX timestamp "sunset": "1661882432", // UNIX timestamp "wind_speed": "4.63 m/s" }
name
: The name of the location.weather_description
: A great, human-readable string to display.temp
: The current temperature.sunrise
,sunset
: UNIX timestamps, which we can easily convert to a readable time.
Step 3: Building the App (HTML, CSS & JavaScript)
Here is the complete code for our simple weather widget. Create a single index.html
file and paste this code into it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Weather App</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f0f2f5; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
.weather-container { background-color: white; padding: 2rem; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); text-align: center; width: 90%; max-width: 400px; }
h1 { margin-top: 0; }
.search-box { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; }
#city-input { flex-grow: 1; padding: 0.75rem; border: 1px solid #ddd; border-radius: 8px; font-size: 1rem; }
#search-btn { padding: 0.75rem 1rem; border: none; background-color: #007bff; color: white; border-radius: 8px; font-size: 1rem; cursor: pointer; }
#search-btn:hover { background-color: #0056b3; }
#weather-result { line-height: 1.6; }
.error { color: #d93025; }
</style>
</head>
<body>
<div class="weather-container">
<h1>Weather Checker</h1>
<div class="search-box">
<input type="text" id="city-input" placeholder="Enter city name">
<button id="search-btn">Search</button>
</div>
<div id="weather-result">
<p>Enter a city to get the current weather.</p>
</div>
</div>
<script>
const apiKey = 'YOUR_API_KEY'; // <-- IMPORTANT: Replace with your actual API key
const cityInput = document.getElementById('city-input');
const searchBtn = document.getElementById('search-btn');
const weatherResultDiv = document.getElementById('weather-result');
searchBtn.addEventListener('click', getWeatherData);
cityInput.addEventListener('keypress', function(event) {
if (event.key === 'Enter') {
getWeatherData();
}
});
async function getWeatherData() {
const city = cityInput.value.trim();
if (!city) {
weatherResultDiv.innerHTML = `<p class="error">Please enter a city name.</p>`;
return;
}
const apiUrl = `https://hub.juheapi.com/weather/v1?key=${apiKey}&q=${encodeURIComponent(city)}`;
weatherResultDiv.innerHTML = `<p>Fetching weather data...</p>`;
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`City not found or API error (Status: ${response.status})`);
}
const result = await response.json();
// Check for API-specific error message
if (result.code !== "OK" || !result.data) {
throw new Error(result.msg || "Invalid data received");
}
displayWeatherData(result.data);
} catch (error) {
console.error("Error fetching weather data:", error);
weatherResultDiv.innerHTML = `<p class="error">${error.message}</p>`;
}
}
function displayWeatherData(data) {
const { name, weather_description, temp, humidity, wind_speed, sunrise, sunset } = data;
// Function to convert UNIX timestamp to readable time
const formatTime = (timestamp) => {
return new Date(timestamp * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};
weatherResultDiv.innerHTML = `
<h2>${name}</h2>
<p><strong>Weather:</strong> ${weather_description}</p>
<p><strong>Temperature:</strong> ${temp}°C</p>
<p><strong>Humidity:</strong> ${humidity}</p>
<p><strong>Wind Speed:</strong> ${wind_speed}</p>
<p><strong>Sunrise:</strong> ${formatTime(sunrise)}</p>
<p><strong>Sunset:</strong> ${formatTime(sunset)}</p>
`;
}
</script>
</body>
</html>
Conclusion & Next Steps
Congratulations! You've successfully built a web application that fetches and displays live data from a real-world REST API. This fundamental skill—making a request, handling the response, and updating the UI—is the foundation for countless more complex and exciting projects.
Ready to add more features?
- Use a library like Chart.js to visualize temperature forecasts.
- Add icons that change based on the
weather_description
. - Explore the full API Documentation to add 5-day forecasts, historical data, or weather map layers.
Happy coding!