接口概述
天气预报1-7天API接口是一个基于地址查询的免费天气数据服务,提供准确、权威的天气预报信息。该接口数据来源于中国气象局官方,覆盖全国各级行政区划,能够返回1-7天的天气预报数据,包括温度、天气状况、风力风向等详细信息,同时还支持时段天气预报功能。
接口基本信息
- 接口类型: RESTful API
- 请求协议: HTTP/HTTPS
- 请求方式: GET或POST
- 返回格式: JSON
- 调用限制: 需使用个人ID和KEY(示例中为公共测试凭证)
核心功能特点
- 多维度数据: 提供白天/夜间天气、温度、风力、湿度、气压等全方位气象数据
- 时段预报: 可获取一天内多个时间点的详细天气情况
- 预警信息: 包含天气预警数据,及时掌握灾害天气信息
- 地理信息: 提供查询地点的经纬度坐标
- 多天预报: 支持1-7天天气预报查询
请求参数详解
参数名 |
必填 |
说明 |
示例 |
id |
是 |
用户ID,用户中心的数字ID |
id=10000000 |
key |
是 |
用户通讯秘钥 |
key=15he5h15ty854j5sr152hs2 |
sheng |
否 |
省份名称(一级行政区) |
sheng=四川省 |
place |
是 |
查询地点(市级或区级名称) |
place=绵阳 |
day |
否 |
查询天数(1-7,默认1) |
day=3 |
hourtype |
否 |
是否返回时段天气(0/1,默认0) |
hourtype=1 |
返回参数解析
基本天气信息
guo: 国家名称sheng: 省级行政区shi: 市级地区name: 具体预报地址
当日天气数据
weather1/weather2: 白天/夜间天气状况wd1/wd2: 白天/夜间温度winddirection1/winddirection2: 白天/夜间风向windleve1/windleve2: 白天/夜间风力等级
实时天气信息
nowinfo: 当前天气数据集
precipitation: 降水量temperature: 温度pressure: 气压humidity: 湿度windSpeed: 风速feelst: 体感温度
预警信息
alarm: 近期预警信息(无预警时返回null)
多天预报
weatherday2至weatherday7: 第2-7天天气预报
时段预报
hour1至hour7: 当天至第7天的时段天气数据
调用示例
PHP调用示例
php
php
复制
<?php /** * 中国气象局天气预报API调用示例(PHP版) */ class WeatherAPI { private $baseUrl = "https://cn.apihz.cn/api/tianqi/tqyb.php"; private $id = "88888888"; // 请替换为您的实际ID private $key = "88888888"; // 请替换为您的实际KEY /** * 获取天气预报 * @param string $province 省份名称 * @param string $city 城市名称 * @param int $days 查询天数(1-7) * @param bool $hourly 是否返回时段天气 * @return array 天气数据 */ public function getWeather($province, $city, $days = 1, $hourly = false) { // 构建请求参数 $params = array( 'id' => $this->id, 'key' => $this->key, 'sheng' => $province, 'place' => $city, 'day' => $days, 'hourtype' => $hourly ? 1 : 0 ); // 构建请求URL $url = $this->baseUrl . '?' . http_build_query($params); // 发送GET请求 $response = file_get_contents($url); // 解析JSON响应 $weatherData = json_decode($response, true); // 检查请求状态 if ($weatherData['code'] != 200) { throw new Exception("API请求失败: " . $weatherData['msg']); } return $weatherData; } /** * 格式化显示天气信息 * @param array $weatherData 天气数据 */ public function displayWeather($weatherData) { echo "=== 天气预报 ===\n"; echo "地区: " . $weatherData['sheng'] . " " . $weatherData['shi'] . "\n"; echo "更新时间: " . $weatherData['uptime'] . "\n\n"; echo "今日天气:\n"; echo "白天: " . $weatherData['weather1'] . ",温度: " . $weatherData['wd1'] . "℃\n"; echo "夜间: " . $weatherData['weather2'] . ",温度: " . $weatherData['wd2'] . "℃\n"; echo "风向: " . $weatherData['winddirection1'] . ",风力: " . $weatherData['windleve1'] . "\n\n"; // 显示实时天气 if (isset($weatherData['nowinfo'])) { echo "实时天气:\n"; echo "温度: " . $weatherData['nowinfo']['temperature'] . "℃\n"; echo "湿度: " . $weatherData['nowinfo']['humidity'] . "%\n"; echo "气压: " . $weatherData['nowinfo']['pressure'] . "hPa\n"; echo "体感温度: " . $weatherData['nowinfo']['feelst'] . "℃\n\n"; } // 显示多天预报 if ($weatherData['day'] > 1) { echo "未来天气预报:\n"; for ($i = 2; $i <= $weatherData['day']; $i++) { $dayKey = 'weatherday' . $i; if (isset($weatherData[$dayKey])) { $dayData = $weatherData[$dayKey]; echo "第{$i}天 (" . $dayData['date'] . "): "; echo $dayData['weather1'] . ",温度: " . $dayData['wd1'] . "~" . $dayData['wd2'] . "℃\n"; } } } } } // 使用示例 try { $weatherAPI = new WeatherAPI(); $weatherData = $weatherAPI->getWeather("四川", "绵阳", 3, true); $weatherAPI->displayWeather($weatherData); } catch (Exception $e) { echo "错误: " . $e->getMessage(); } ?>
Python调用示例
python
python
下载
复制
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 中国气象局天气预报API调用示例(Python版) """ import requests import json from typing import Dict, Any, Optional class WeatherAPI: def __init__(self): self.base_url = "https://cn.apihz.cn/api/tianqi/tqyb.php" self.id = "88888888" # 请替换为您的实际ID self.key = "88888888" # 请替换为您的实际KEY def get_weather(self, province: str, city: str, days: int = 1, hourly: bool = False) -> Dict[str, Any]: """ 获取天气预报数据 Args: province: 省份名称 city: 城市名称 days: 查询天数(1-7) hourly: 是否返回时段天气 Returns: Dict[str, Any]: 天气数据字典 Raises: Exception: API请求失败时抛出异常 """ # 构建请求参数 params = { 'id': self.id, 'key': self.key, 'sheng': province, 'place': city, 'day': days, 'hourtype': 1 if hourly else 0 } try: # 发送GET请求 response = requests.get(self.base_url, params=params, timeout=10) response.raise_for_status() # 解析JSON响应 weather_data = response.json() # 检查请求状态 if weather_data.get('code') != 200: raise Exception(f"API请求失败: {weather_data.get('msg', '未知错误')}") return weather_data except requests.exceptions.RequestException as e: raise Exception(f"网络请求失败: {str(e)}") except json.JSONDecodeError as e: raise Exception(f"JSON解析失败: {str(e)}") def display_weather(self, weather_data: Dict[str, Any]) -> None: """格式化显示天气信息""" print("=== 天气预报 ===") print(f"地区: {weather_data.get('sheng', '')} {weather_data.get('shi', '')}") print(f"更新时间: {weather_data.get('uptime', '')}\n") print("今日天气:") print(f"白天: {weather_data.get('weather1', '')},温度: {weather_data.get('wd1', '')}℃") print(f"夜间: {weather_data.get('weather2', '')},温度: {weather_data.get('wd2', '')}℃") print(f"风向: {weather_data.get('winddirection1', '')},风力: {weather_data.get('windleve1', '')}\n") # 显示实时天气 nowinfo = weather_data.get('nowinfo') if nowinfo: print("实时天气:") print(f"温度: {nowinfo.get('temperature', '')}℃") print(f"湿度: {nowinfo.get('humidity', '')}%") print(f"气压: {nowinfo.get('pressure', '')}hPa") print(f"体感温度: {nowinfo.get('feelst', '')}℃\n") # 显示预警信息 alarm = weather_data.get('alarm') if alarm: print("天气预警:") print(f"标题: {alarm.get('title', '')}") print(f"等级: {alarm.get('signallevel', '')}") print(f"生效时间: {alarm.get('effective', '')}\n") # 显示多天预报 days = weather_data.get('day', 1) if days > 1: print("未来天气预报:") for i in range(2, days + 1): day_key = f'weatherday{i}' day_data = weather_data.get(day_key) if day_data: print(f"第{i}天 ({day_data.get('date', '')}): {day_data.get('weather1', '')}," f"温度: {day_data.get('wd1', '')}~{day_data.get('wd2', '')}℃") # 显示时段预报(如果存在) if weather_data.get('hourtype') == 1: print("\n今日时段预报:") hour1 = weather_data.get('hour1', []) for hour in hour1: print(f"{hour.get('时间', '')}: {hour.get('天气', '')}," f"温度: {hour.get('气温', '')},降水: {hour.get('降水', '')}") def main(): """主函数示例""" try: # 创建API实例 weather_api = WeatherAPI() # 获取天气数据(四川省绵阳市,3天预报,包含时段数据) weather_data = weather_api.get_weather("四川", "绵阳", days=3, hourly=True) # 显示天气信息 weather_api.display_weather(weather_data) # 可选:保存原始数据到文件 with open('weather_data.json', 'w', encoding='utf-8') as f: json.dump(weather_data, f, ensure_ascii=False, indent=2) print("\n原始数据已保存到 weather_data.json") except Exception as e: print(f"错误: {str(e)}") if __name__ == "__main__": main()
高级使用技巧
错误处理最佳实践
- 网络异常处理: 实现重试机制应对网络波动
- 参数验证: 确保输入参数符合API要求
- 频率限制: 遵守API调用频率限制,避免被封禁
数据缓存策略
python
python
下载
复制
# 简单的缓存实现示例 import time from typing import Dict, Any class CachedWeatherAPI(WeatherAPI): def __init__(self, cache_ttl: int = 600): # 默认缓存10分钟 super().__init__() self.cache_ttl = cache_ttl self._cache: Dict[str, Any] = {} self._cache_timestamp: Dict[str, float] = {} def get_weather_cached(self, province: str, city: str, days: int = 1, hourly: bool = False) -> Dict[str, Any]: # 生成缓存键 cache_key = f"{province}_{city}_{days}_{hourly}" # 检查缓存是否有效 current_time = time.time() if (cache_key in self._cache and current_time - self._cache_timestamp.get(cache_key, 0) < self.cache_ttl): return self._cache[cache_key] # 获取新数据并更新缓存 weather_data = self.get_weather(province, city, days, hourly) self._cache[cache_key] = weather_data self._cache_timestamp[cache_key] = current_time return weather_data
批量查询处理
对于需要查询多个城市的情况,建议:
- 合理安排查询间隔,避免频繁请求
- 使用异步请求提高效率
- 实现错误重试和降级处理
应用场景
- 天气预报应用: 开发手机或网页版天气预报工具
- 出行规划: 为旅行、户外活动提供天气参考
- 农业应用: 为农业生产提供气象数据支持
- 数据分析: 结合历史天气数据进行趋势分析
- 智能家居: 根据天气情况自动调节家居设备
注意事项
- 认证信息: 务必使用个人ID和KEY,避免使用公共测试凭证
- 数据更新: 天气数据具有时效性,注意及时更新
- 使用限制: 遵守API提供商的使用条款和频率限制
- 错误处理: 完善错误处理机制,提高应用稳定性
- 数据版权: 尊重数据版权,合规使用气象数据
通过本文的详细介绍和代码示例,并将其集成到各种应用中,为用户提供准确、及时的天气信息服务。