Python Weather Data API Fetcher
Fetch real-time weather details in Python using standard libraries. Learn API requests, JSON conversions, and mock fallbacks.
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.
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}¤t_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)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/hReal-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
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Check Data Type in Python
Learn how to check data types in Python. Understand when to use type() vs isinstance(), handle custom classes, and write safe type check validations.
Python Collections & Data Structures
Complete guide to Python collections module and native data structures. Learn lists, dicts, sets, tuples, deques, and namedtuples.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.