IP查询天气API为开发者提供了便捷的天气预报服务。该服务通过调用者IP自动定位地区,并返回精准的天气数据,数据来源权威可靠。本文将详细介绍该API的使用方法及调用示例。
一、API核心功能
- 智能定位:自动识别调用者IP地址所属地区
- 灵活调用:支持GET/POST两种请求方式
- 精准返回:提供温度、湿度、风向风速等15项气象数据
二、请求参数说明
参数名 | 必填 | 说明 |
---|---|---|
id | 是 | 用户中心的数字ID |
key | 是 | 用户中心通讯秘钥 |
ip | 否 | 要查询的IP地址(默认使用调用者IP) |
注意:请前往接口盒子官网注册获取专属ID和KEY,避免使用示例中的公共密钥导致限流。
三、返回参数说明
返回JSON格式数据,主要字段包括:
code
:状态码(200成功/400错误)msg
:错误提示信息temperature
:当前温度(℃)humidity
:湿度百分比windDirection
:风向描述windSpeed
:风速(m/s)place
:地理位置信息weather1
/weather2
:组合天气状态
完整返回示例:
json
复制
{
"precipitation": 0,
"temperature": 32.9,
"pressure": 1010,
"humidity": 53,
"windDirection": "东北风",
"windDirectionDegree": 17,
"windSpeed": 1.2,
"windScale": "微风",
"code": 200,
"place": "中国, 上海, 徐家汇",
"weather1": "多云",
"weather2": "晴",
"ip": "49.234.56.78"
}
四、调用示例代码
1. PHP调用示例
php
复制
<?php
$apiUrl = "https://cn.apihz.cn/api/tianqi/tqybip.php";
$userId = "10000000"; // 替换为您的实际ID
$userKey = "15he5h15ty854j5sr152hs2"; // 替换为您的实际KEY
$targetIp = "49.234.56.78"; // 可选参数
// 构建请求URL
$requestUrl = $apiUrl . "?id=" . $userId . "&key=" . $userKey . "&ip=" . $targetIp;
// 发送GET请求
$response = file_get_contents($requestUrl);
// 处理返回结果
$weatherData = json_decode($response, true);
if ($weatherData['code'] == 200) {
echo "当前位置:" . $weatherData['place'] . "\n";
echo "当前温度:" . $weatherData['temperature'] . "℃\n";
echo "天气状况:" . $weatherData['weather1'] . "转" . $weatherData['weather2'];
} else {
echo "请求失败:" . $weatherData['msg'];
}
?>
2. Python调用示例
python
运行
复制
import requests
api_url = "https://cn.apihz.cn/api/tianqi/tqybip.php"
user_id = "10000000" # 替换为您的实际ID
user_key = "15he5h15ty854j5sr152hs2" # 替换为您的实际KEY
target_ip = "49.234.56.78" # 可选参数
# 构建请求参数
params = {
"id": user_id,
"key": user_key,
"ip": target_ip
}
# 发送GET请求
response = requests.get(api_url, params=params)
weather_data = response.json()
if weather_data["code"] == 200:
print(f"当前位置:{weather_data['place']}")
print(f"当前温度:{weather_data['temperature']}℃")
print(f"天气状况:{weather_data['weather1']}转{weather_data['weather2']}")
else:
print(f"请求失败:{weather_data['msg']}")
五、使用注意事项
- 密钥安全:请妥善保管您的KEY,避免泄露
- 频率限制:共享账号每分钟限流,建议使用自有账号
- 数据缓存:建议本地缓存数据,避免频繁调用
- 错误处理:务必检查code状态码后再处理数据
- 数据更新:气象数据每30分钟更新一次
通过这个免费API,开发者可以轻松将精准天气预报功能集成到各类应用中,无论是网站、移动应用还是物联网设备,都能为用户提供实时可靠的天气信息服务。