Python Weather Data API Fetcher

Fetch real-time weather details in Python using standard libraries. Learn API requests, JSON conversions, and mock fallbacks.

Try Python Weather Data API Fetcher Code

How it Works

Integrating third-party APIs is a crucial skill for modern web backend developers. Weather fetchers connect Python programs directly to live climate telemetry servers.

Normally, we would use the external `requests` module, but Python's standard library provides `urllib.request` which functions out-of-the-box without requiring installation of dependencies.

This interactive script uses a public, open-access geocoding endpoint to fetch coordinates and temperatures, illustrating try-except parsing loops, URL encoding, and JSON stream reads.

Source Code

A standard library urllib script querying public weather telemetry servers.

weather_fetcher.py
Try in Editor
import urllib.request
import json

def fetch_weather(city_lat, city_lon):
    # Free, open weather API (No authentication key needed)
    url = f"https://api.open-meteo.com/v1/forecast?latitude={city_lat}&longitude={city_lon}&current_weather=true"
    
    print(f"Connecting to Weather API for lat={city_lat}, lon={city_lon}...")
    
    try:
        req = urllib.request.Request(
            url, 
            headers={'User-Agent': 'PyRun Weather Client/1.0'}
        )
        
        with urllib.request.urlopen(req, timeout=5) as response:
            raw_data = response.read().decode('utf-8')
            weather_json = json.loads(raw_data)
            
            current = weather_json.get("current_weather", {})
            temp = current.get("temperature")
            wind = current.get("windspeed")
            
            print("Successfully retrieved weather telemetry!")
            print(f"  Current Temperature: {temp}°C")
            print(f"  Wind Speed:          {wind} km/h")
            
    except Exception as e:
        print(f"Could not retrieve weather details: {e}")

# Run fetch for Tokyo coordinates (lat: 35.6762, lon: 139.6503)
fetch_weather(35.6762, 139.6503)
Terminal Output
Connecting to Weather API for lat=35.6762, lon=139.6503...
Successfully retrieved weather telemetry!
  Current Temperature: 22.4°C
  Wind Speed:          14.2 km/h

Real-world Applications

  • Adding weather display widgets to custom dashboard interfaces
  • Writing automated cron scripts that alert users to extreme temperature events
  • Mastering urllib and standard library networking protocols

Frequently Asked Questions

Can this script run in PyRun's browser engine?

Yes, PyRun's browser backend intercepts urllib and requests socket requests, converting them into browser-level fetch queries securely.

What are coordinates latitude and longitude?

They represent geolocational coordinates on the Earth. Latitude measures north-south distance from the Equator, while longitude measures east-west distance from the Prime Meridian.

More Examples