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

  1. Register on OpenWeatherMap and get a free API key.
  2. Get the city name from an HTML input field.
  3. Build the request URL.
  4. Fetch and parse the JSON response.
  5. 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!