Putting It All Together
Time to use everything we've learned to build a real project: a weather app using a live public API.
The Plan
- Register on OpenWeatherMap and get a free API key.
- Get the city name from an HTML input field.
- Build the request URL.
- Fetch and parse the JSON response.
- Display temperature and weather description on the page.
const API_KEY = 'your_api_key_here';
async function getWeather(city) {
const url = new URL('https://api.openweathermap.org/data/2.5/weather');
url.searchParams.set('q', city);
url.searchParams.set('appid', API_KEY);
url.searchParams.set('units', 'metric'); // Celsius
const response = await fetch(url);
if (!response.ok) {
throw new Error(response.status === 404 ? 'City not found!' : 'Server error');
}
const data = await response.json();
document.querySelector('#city-name').textContent = data.name;
document.querySelector('#temperature').textContent = Math.round(data.main.temp) + '°C';
document.querySelector('#description').textContent = data.weather[0].description;
document.querySelector('#humidity').textContent = 'Humidity: ' + data.main.humidity + '%';
}
document.querySelector('#search-btn').addEventListener('click', () => {
const city = document.querySelector('#city-input').value;
getWeather(city).catch(err => alert(err.message));
});
Tip
Working with real APIs is the fastest way to feel like a real developer. The same pattern works for hundreds of different public APIs — news, currency rates, movies, recipes — the world is your oyster!