Back to Tutorials

Integrating Third-Party APIs: Weather App Example

Introduction

Most modern apps integrate with third-party APIs to add functionality. In this tutorial, we'll build a weather app using a public weather API.

Choosing an API

Popular weather APIs:

  • OpenWeatherMap: Free tier available, comprehensive data
  • WeatherAPI: Simple and reliable
  • AccuWeather: Professional-grade data

Getting API Keys

Most APIs require registration and an API key:

  1. Sign up at the API provider's website
  2. Generate an API key
  3. Store it securely (use environment variables)

Building the Weather App

// server.js - Backend proxy to avoid CORS issues
const express = require('express');
const axios = require('axios');
require('dotenv').config();

const app = express();
app.use(express.json());

// Proxy endpoint to fetch weather
app.get('/api/weather/:city', async (req, res) => {
  try {
    const city = req.params.city;
    const API_KEY = process.env.WEATHER_API_KEY;
    const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`;
    
    const response = await axios.get(url);
    res.json({
      city: response.data.name,
      temperature: response.data.main.temp,
      description: response.data.weather[0].description,
      humidity: response.data.main.humidity,
      windSpeed: response.data.wind.speed
    });
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch weather data' });
  }
});

app.listen(3000, () => console.log('Server running on port 3000'));

Frontend Implementation

<!DOCTYPE html>
<html>
<head>
  <title>Weather App</title>
  <style>
    body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
    input { padding: 10px; font-size: 16px; }
    button { padding: 10px 20px; font-size: 16px; }
    .weather-card { margin-top: 30px; padding: 20px; border: 1px solid #ddd; border-radius: 10px; }
  </style>
</head>
<body>
  <h1>Weather App</h1>
  <input type="text" id="cityInput" placeholder="Enter city name">
  <button onclick="getWeather()">Get Weather</button>
  <div id="weather"></div>

  <script>
    async function getWeather() {
      const city = document.getElementById('cityInput').value;
      if (!city) return;

      try {
        const response = await fetch(`http://localhost:3000/api/weather/${city}`);
        const data = await response.json();
        
        document.getElementById('weather').innerHTML = `
          <div class="weather-card">
            <h2>${data.city}</h2>
            <p>Temperature: ${data.temperature}°C</p>
            <p>Description: ${data.description}</p>
            <p>Humidity: ${data.humidity}%</p>
            <p>Wind Speed: ${data.windSpeed} m/s</p>
          </div>
        `;
      } catch (error) {
        alert('Error fetching weather data');
      }
    }
  </script>
</body>
</html>

Best Practices

  • API Key Security: Never expose API keys in frontend code
  • Error Handling: Always handle API failures gracefully
  • Rate Limiting: Be aware of API rate limits
  • Caching: Cache API responses when appropriate
  • Fallbacks: Provide fallback data if API fails

Common API Patterns

  • REST APIs: Standard HTTP methods (GET, POST, PUT, DELETE)
  • GraphQL: Query language for APIs
  • WebSockets: Real-time bidirectional communication