利用showapi提供的接口,根据地名查询天气预报

一、前置准备

注册与开通服务

访问万维易源官网(https://www.showapi.com/)注册账号并实名认证。

找到 "天气预报" API 并开通,获取 showapi_appid(应用 ID)与 showapi_sign(密钥),在控制台可查看。

接口选择(常用)

接口用途 接口地址 核心参数 备注

实时 + 7 天预报 https://route.showapi.com/92 area(地名)、showapi_appid、showapi_sign 支持 3 小时粒度预报,数据 30 分钟更新一次

未来 40 天预报 https://route.showapi.com/9-12 area(地名)、showapi_appid、showapi_sign 每天 3 次更新,建议优先用 areaCode 避免重名

地名转区域 ID https://route.showapi.com/9-3 area(地名)、showapi_appid、showapi_sign 解决地名重名问题,获取 areaCode 后再查天气

二、调用流程与示例

  1. 核心请求参数(通用)
    参数 是否必填 说明
    showapi_appid 是 应用唯一标识,控制台获取
    showapi_sign 是 接口密钥,用于签名验证
    area 是 地名(如 "北京""上海"),与 areaCode 二选一,重名时取第一条记录
    need3HourForcast 否 1 = 需要 3 小时预报,0 = 不需要(默认 0)
    needAlarm 否 1 = 需要天气预警,0 = 不需要(默认 0)
  2. 调用示例(以实时 + 7 天预报为例)
    请求 URL(替换占位符):
    plaintext
    https://route.showapi.com/92?showapi_appid=你的APPID&showapi_sign=你的密钥&area=北京&need3HourForcast=1
    发送 GET 请求(可通过 Postman、curl 或代码实现)。
    curl 命令示例:
    bash
    运行
    curl "https://route.showapi.com/92?showapi_appid=xxx&showapi_sign=xxx&area=北京"
  3. 响应结果解析(JSON 格式)
    成功时 showapi_res_code 为 0,核心数据在 showapi_res_body 中:
    json
    {
    "showapi_res_code": 0,
    "showapi_res_error": "",
    "showapi_res_body": {
    "now": { "temp": "2℃", "weather": "晴", "wind_direction": "北风" },
    "f1": { "day_weather": "晴", "day_temp": "8℃", "night_temp": "-3℃" },
    "f2": { ... }
    }
    }
    now:当前天气实况(温度、天气、风向等)。
    f1~f7:未来 7 天预报(日 / 夜天气、温度等)。
    若 need3HourForcast=1,会返回 hourly_forecast 数组,包含每 3 小时预报。
    三、代码实现(Python 示例)
    python
    运行
    import requests

def get_weather_by_area(area, appid, sign):

url = "https://route.showapi.com/92"

params = {

"showapi_appid": appid,

"showapi_sign": sign,

"area": area,

"need3HourForcast": 1

}

response = requests.get(url, params=params)

result = response.json()

if result["showapi_res_code"] == 0:

return result["showapi_res_body"]

else:

raise Exception(f"请求失败:{result['showapi_res_error']}")

使用示例

if name == "main ":

APPID = "你的APPID"

SIGN = "你的密钥"

weather_data = get_weather_by_area("上海", APPID, SIGN)

print("当前温度:", weather_data["now"]["temp"])

print("今日天气:", weather_data["f1"]["day_weather"])

四、常见问题与注意事项

地名重名问题:优先调用 9-3 接口获取 areaCode,再用 areaCode 查询天气,避免结果错误。

签名错误:检查 showapi_appid 与 showapi_sign 是否匹配,密钥是否泄露。

频率限制:不同套餐有调用次数限制,超出会返回 403 或 503,可在控制台查看配额。

数据更新:实时天气 30 分钟更新,7 天预报每天 3 次更新,40 天预报每天 3 次更新。

五、扩展建议

缓存机制:对同一地名的查询结果缓存 10--30 分钟,减少接口调用次数。

异常处理:捕获网络错误、响应超时、参数错误等,返回友好提示。

重名处理:调用 9-3 接口获取所有匹配的 areaCode,让用户选择正确区域后再查询天气。