import requests
# API endpoint and API key
api_url = "https://api.openweathermap.org/data/2.5/weather"
api_key = "your_api_key_here"
# Parameters to send in the API request
params = {
"q": "New York", # City name
"appid": api_key, # API key
"units": "metric", # Units: metric for Celsius
"lang": "en", # Language for weather description
"mode": "json" # Response format: JSON
}
# optional
# headers = {
# 'Authorization': 'Bearer YOUR_API_TOKEN',
# 'Content-Type': 'application/json',
# 'Accept': 'application/json'
# }
try:
# Send the GET request with all parameters
response = requests.get(api_url, params=params)
response.raise_for_status() # Raise an error for HTTP issues
# Parse the JSON response
data = response.json()
# Select specific fields from the response
selected_data = {
"city": data["name"],
"temperature": data["main"]["temp"],
"humidity": data["main"]["humidity"],
"pressure": data["main"]["pressure"],
"wind_speed": data["wind"]["speed"],
"description": data["weather"][0]["description"]
}
# Print the selected data
print("Selected Weather Data:")
print(selected_data)
except requests.exceptions.RequestException as e:
print(f"Error fetching data: {e}")
except KeyError as e:
print(f"Error selecting fields: {e}")