Project: a weather app in JavaScript
You ask for a city, call an API with fetch, and render a card with the result. Error handling included.
The weather app is the "hello world" of consuming APIs: you request data from a server, wait for the response and show it. It combines fetch, async/await, JSON and the DOM.
Demo
Escribe una ciudad. La API es simulada (Madrid, Bilbao, Barcelona, Valencia, Sevilla, Santiago de Compostela). Prueba también una que no exista:
Step 1: the HTML
<form id="form">
<input type="text" id="ciudad" placeholder="Ciudad">
<button>Consultar</button>
</form>
<div id="resultado"></div>
Step 2: request the data with fetch
const API = "https://api.openweathermap.org/data/2.5/weather";
const CLAVE = "TU_API_KEY"; // se saca gratis registrándote
async function pedirTiempo(ciudad) {
const url = `${API}?q=${ciudad}&appid=${CLAVE}&units=metric&lang=es`;
const res = await fetch(url);
if (!res.ok) throw new Error("Ciudad no encontrada"); // 404
return res.json();
}
Step 3: render the result
function pintar(datos) {
document.getElementById("resultado").innerHTML = `
<h2>${datos.name}</h2>
<p class="temp">${Math.round(datos.main.temp)}°C</p>
<p>${datos.weather[0].description}</p>
`;
}
Step 4: put it together and handle errors
document.getElementById("form").addEventListener("submit", async (e) => {
e.preventDefault();
const ciudad = document.getElementById("ciudad").value.trim();
if (!ciudad) return;
const salida = document.getElementById("resultado");
salida.textContent = "Cargando...";
try {
const datos = await pedirTiempo(ciudad);
pintar(datos);
} catch (err) {
salida.textContent = "⚠️ " + err.message; // no dejes al usuario sin feedback
}
});
try/catch around the await is what separates a professional app from one that breaks silently.Where to go next
- Request the weather for the next 5 days (another endpoint).
- Use the browser's geolocation for the current city.
- Save the last searched city in
localStorage. - Change the background depending on sun, rain or snow.