接入教程
1. 访问Weatherstack官网注册账号获取API密钥。2. 使用提供的API端点(如`http://api.weatherstack.com/current`)进行HTTP请求。3. 在请求参数中指定`access_key`和查询地点(如`query=New York`)。4. 解析返回的JSON数据以获取天气信息。
获取当前天气数据
python
import requests
api_key = 'YOUR_API_KEY'
city = 'Beijing'
url = f'https://api.weatherstack.com/current?access_key={api_key}&query={city}'
response = requests.get(url)
data = response.json()
if response.status_code == 200:
print(f"温度: {data['current']['temperature']}°C")
print(f"天气描述: {data['current']['weather_descriptions'][0]}")
else:
print(f"请求失败: {data.get('error', 'Unknown error')}")
查询历史天气
php
<?php
$api_key = 'YOUR_API_KEY';
$city = 'Shanghai';
$date = '2023-10-01';
$url = "https://api.weatherstack.com/historical?access_key={$api_key}&query={$city}&historical_date={$date}";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if (isset($data['historical'])) {
echo "历史温度: " . $data['historical'][$date]['avgtemp'] . "°C\n";
} else {
echo "错误: " . ($data['error']['info'] ?? '未知错误') . "\n";
}
?>
使用Fetch获取天气预报
javascript
const apiKey = 'YOUR_API_KEY';
const city = 'Guangzhou';
const url = `https://api.weatherstack.com/forecast?access_key=${apiKey}&query=${city}&forecast_days=3`;
fetch(url)
.then(response => response.json())
.then(data => {
if (data.current) {
console.log(`当前温度: ${data.current.temperature}°C`);
console.log(`天气预报: ${data.forecast[Object.keys(data.forecast)[0]].avgtemp}°C 平均温度`);
} else {
console.error('错误:', data.error?.info || '未知错误');
}
})
.catch(error => console.error('请求失败:', error));
常见问题
Weatherstack API的免费套餐有哪些限制?
免费套餐每月提供1000次请求额度,仅支持当前天气查询,不包含历史数据和天气预报功能,且每小时限速100次请求。
如何解决API返回"invalid_access_key"错误?
请检查API密钥是否正确输入,确保没有多余空格。如果确认密钥正确但仍报错,可能是账户未激活或套餐已过期,请登录官网账户页面核实状态。
API支持哪些查询格式的地点参数?
支持城市名称(如"Beijing")、邮政编码(如"100101")、经纬度坐标(如"39.9042,116.4074")和IP地址(如"134.201.250.155")等多种查询格式。
Aitishiku.com