要正确调用Weatherstack的HTTP API GET请求,请遵循以下步骤:
http://api.weatherstack.com/current?access_key=YOUR_ACCESS_KEY&query=QUERY
将YOUR_ACCESS_KEY
替换为您的API密钥,将QUERY
替换为您想查询天气的城市、地区或邮政编码。
例如,要查询纽约市的当前天气,URL应为:
http://api.weatherstack.com/current?access_key=YOUR_ACCESS_KEY&query=New%20York
注意,城市名称应使用URL编码(例如,空格替换为%20
)。
import requests
api_key = "YOUR_ACCESS_KEY"
query = "New York"
url = f"http://api.weatherstack.com/current?access_key={api_key}&query={query}"
response = requests.get(url)
weather_data = response.json()
print(weather_data)
const apiKey = "YOUR_ACCESS_KEY";
const query = "New York";
const url = `http://api.weatherstack.com/current?access_key=${apiKey}&query=${encodeURIComponent(query)}`;
fetch(url)
.then((response) => response.json())
.then((weatherData) => {
console.log(weatherData);
})
.catch((error) => {
console.error("Error fetching weather data:", error);
});
curl "http://api.weatherstack.com/current?access_key=YOUR_ACCESS_KEY&query=New%20York"
例如,在Python中,您可以使用json
库解析JSON响应:
import json
weather_json = json.dumps(weather_data, indent=2)
print(weather_json)
# 提取特定信息,如温度
temperature = weather_data['current']['temperature']
print(f"Temperature in {query}: {temperature}°C")
在JavaScript中,您可以直接访问解析后的JSON对象的属性:
const temperature = weatherData.current.temperature;
console.log(`Temperature in ${query}: ${temperature}°C`);
现在,您已经知道如何正确调用Weatherstack的HTTP API GET请求并处理返回的天气数据。请确保将YOUR_ACCESS_KEY
替换为您的实际API密钥,并根据需要修改查询参数。
没有搜到相关的文章