Beginner 10 minutes

Your First Weather API Call

Learn to fetch weather data in 10 minutes. Get current temperature, humidity, and conditions for any city in the world.

What You'll Build

A script that fetches current weather data for any city and displays temperature, humidity, and weather conditions.

Prerequisites

  • Basic JavaScript knowledge
  • A code editor or browser console
1

Get your API key

Sign up at openweathermap.org and navigate to 'API keys' in your account dashboard. Copy your default API key. The free tier allows 60 calls per minute, which is plenty for learning.

2

Fetch current weather

Use the fetch API to call the OpenWeatherMap current weather endpoint. We pass the city name and use metric units for Celsius temperatures.

javascript
const city = 'London';
const apiKey = 'YOUR_API_KEY';

const response = await fetch(
  `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`
);
const data = await response.json();

console.log(`City: ${data.name}`);
console.log(`Temperature: ${data.main.temp}°C`);
console.log(`Humidity: ${data.main.humidity}%`);
console.log(`Conditions: ${data.weather[0].description}`);
3

Handle errors gracefully

Always check the response status to handle cases like invalid city names or API key issues.

javascript
async function getWeather(city) {
  const apiKey = 'YOUR_API_KEY';
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`;

  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`City not found (${response.status})`);
    }
    const data = await response.json();
    return {
      city: data.name,
      temp: data.main.temp,
      humidity: data.main.humidity,
      description: data.weather[0].description
    };
  } catch (error) {
    console.error('Error:', error.message);
    return null;
  }
}

const weather = await getWeather('Tokyo');
if (weather) {
  console.log(`${weather.city}: ${weather.temp}°C, ${weather.description}`);
}

Next Steps

  • Try fetching weather for different cities
  • Add a 5-day forecast using the /forecast endpoint
  • Display weather icons using the icon codes in the response