[go: up one dir, main page]

0% found this document useful (0 votes)
12 views1 page

API Request

Uploaded by

pratyush.0657
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views1 page

API Request

Uploaded by

pratyush.0657
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

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}")

You might also like