和风天气预报接口Python SDK

一、介绍

和风天气接口是目前市面上为数不多的提供专业天气预报服务的平台。

 

二、和风天气服务及数据

服务和数据

和风天气开发服务基于先进的气象和人工智能算法,为广大开发者和企业提供了丰富、精准的天气数据服务,帮助你在应用中展示天气,或助力你的业务决策。这一切都可以通过我们提供的开发工具,轻松的集成。

服务 

和风天气开发服务提供下列开发服务:

  • API
  • iOS SDK
  • Android SDK
  • 批量下载(目前为beta版本,2023年一季度正式发布)
  • 可视化气象地图开发工具包(目前为beta版本,2023年一季度正式发布)

你可以通过上述服务在全球范围内,轻松快速的获取各类天气数据服务。

数据 

我们支持中国(包括港澳台)及全球200+国家或地区的气象数据服务,城市或地区总数量超过20万个。

天气类 

数据项目更新频率时间颗粒度时间范围地理范围
实况天气 15分钟 实时 实时 全球
逐天预报 8小时 逐天 1-30天 全球
逐小时预报 1小时 逐小时 1-168小时 全球
POI实况天气 1小时 实时 实时 全球
POI逐天预报 8小时 逐天 1-7天 全球
格点实况天气 20分钟 实时 实时 全球
格点逐天预报 12小时 逐天 1-7天 全球
格点逐小时预报 1小时 逐小时 1-72小时 全球
分钟级降水 5分钟 5分钟 1-2小时 中国

天气指数 

数据项目更新频率时间颗粒度时间范围地理范围
洗车指数 1小时 逐天 1-3天 全球
穿衣指数 1小时 逐天 1-4天 全球
运动指数 1小时 逐天 1-5天 全球
紫外线指数 1小时 逐天 1-6天 全球
钓鱼指数 1小时 逐天 1-7天 全球
舒适度指数 1小时 逐天 1-8天 中国
感冒指数 1小时 逐天 1-9天 中国
旅游指数 1小时 逐天 1-10天 中国
空气污染扩散条件指数 1小时 逐天 1-11天 中国
空调开启指数 1小时 逐天 1-12天 中国
过敏指数 1小时 逐天 1-13天 中国
太阳镜指数 1小时 逐天 1-14天 中国
化妆指数 1小时 逐天 1-15天 中国
晾晒指数 1小时 逐天 1-16天 中国
交通指数 1小时 逐天 1-17天 中国
防晒指数 1小时 逐天 1-18天 中国

空气类 

数据项目更新频率时间颗粒度时间范围地理范围
空气质量实况 1小时 实时 实时 中国
空气质量预报 1小时 逐天 1-5天 中国

预警类 

数据项目更新频率时间颗粒度时间范围地理范围
灾害预警 5分钟 实时 实时 中国,欧盟国家
灾害预警城市列表 5分钟 实时 实时 中国,欧盟国家

天文类 

数据项目更新频率时间颗粒度时间范围地理范围
日出日落时间 24小时 逐天 1-60天 中国
月升月落时间 24小时 逐天 1-60天 全球
月相 24小时 逐天、逐小时 1-60天 全球

海洋类 

数据项目更新频率时间颗粒度时间范围地理范围
潮汐 24小时 逐天 1-3天 全球
潮流 24小时 逐天 1-3天 全球

热带气旋(台风) 

数据项目更新频率时间颗粒度时间范围地理范围
台风列表 1小时 逐天 365天 全球
台风预报 1小时 逐小时 1-72小时 全球
台风位置和路径 1小时 逐小时 台风生命周期 全球

 

三、API

 

GeoAPI

和风天气GeoAPI提供全球地理位位置、全球城市搜索服务,支持经纬度坐标反查、多语言、模糊搜索等功能。

城市搜索

热门城市查询

POI搜索

POI范围搜索

城市天气

城市天气预报提供包括中国3000+市县区在内的全球20万+城市的天气预报,支持实时天气、最多30天预报及最多7天逐小时天气预报。

实时天气

每日天气预报

逐小时天气预报

分钟预报

分钟级降水API(临近预报)支持中国1公里精度的分钟级降雨预报数据,为每一分钟的降雨进行精准预测。

分钟级降水

格点天气

以经纬度为基准的全球高精度、公里级、格点化天气预报产品,包括任意经纬度的实时天气和天气预报。

格点实时天气

格点每日天气预报

格点逐小时天气预报

预警

和风天气灾害预警API提供了全球极端天气预警服务,覆盖中国及全球数十个国家或地区。

天气灾害预警

天气预警城市列表

天气指数

天气生活指数包括洗车指数、穿衣指数、感冒指数、过敏指数、紫外线指数、钓鱼指数等数据。天气指数支持中国3000+个市县区和海外15万个城市天气预报。

天气指数预报

空气质量(new)

全球空气质量API,适配当地空气质量标准,可以轻松的获取指定位置的空气质量、污染物和健康建议。目前已经覆盖100多个国家或地区数据,包括实时和预报数据,分辨率为1x1公里。

实时空气质量(new)

空气质量小时预报(new)

空气质量每日预报(new)

监测站数据(new)

空气质量

中国3000+市县区及1700+监测站点的空气质量AQI数据,包括空气质量(AQI)实时数据,空气质量未来5天预报。

实时空气质量

空气质量每日预报

时光机

时光机可以获取最近10天的历史天气和空气质量数据。

天气时光机

空气质量时光机

热带气旋(台风)

热带气旋(台风)API提供全球主要海洋流域的台风信息,包括台风实时位置、等级、气压、风速,还可查询台风路径和台风预报信息。

台风预报

台风实况和路径

台风列表

海洋数据

海洋数据API提供全球主要港口和城市的潮汐和潮流数据。

潮汐

潮流

太阳辐射

太阳辐射API支持获取全球任意坐标的辐射数据,包括净太阳辐射,太阳散射辐射和太阳直接辐射。

太阳辐射逐小时预报

天文

天文API提供了全球任意地点未来60天的日出日落、太阳高度角、月升月落和月相数据,

日出日落

月升月落和月相

太阳高度角

 

四、和风天气预报接口Python SDK

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

r'''
# 手工测试
C:\Users\taojin>curl -X GET --compressed -H "X-QW-Api-Key: c863bab7a74d437bae4c9147056a1234" "https://devapi.qweather.com/v7/weather/now?location=101010100"
{"code":"200","updateTime":"2025-03-28T11:26+08:00","fxLink":"https://www.qweather.com/en/weather/beijing-101010100.html","now":{"obsTime":"2025-03-28T11:24+08:00","temp":"6","feelsLike":"-2","icon":"104","text":"阴","wind360":"225","windDir":"西南风","windScale":"5","windSpeed":"33","humidity":"33","precip":"0.0","pressure":"1021","vis":"20","cloud":"100","dew":"-11"},"refer":{"sources":["QWeather"],"license":["CC BY-SA 4.0"]}}

C:\Users\fangcheng>curl -X GET --compressed -H "X-QW-Api-Key: c863bab7a74d437bae4c9147056a1234" "https://api.qweather.com/v7/historical/weather?location=101010100&date=20250325"
{"error":{"status":403,"type":"https://dev.qweather.com/docs/resource/error-code/#error-host","title":"Error Host","detail":"Access to the standard subscription HOST with the free subscription KEY is prohibited, and vice versa."}}

C:\Users\fangcheng>curl -X GET --compressed -H "X-QW-Api-Key: c863bab7a74d437bae4c9147056a1234" "https://devapi.qweather.com/v7/astronomy/sun?location=101010100&date=20250329"
{"code":"200","updateTime":"2025-03-28T11:00+08:00","fxLink":"https://www.qweather.com/en/weather/beijing-101010100.html","sunrise":"2025-03-29T06:05+08:00","sunset":"2025-03-29T18:35+08:00","refer":{"sources":["QWeather"],"license":["CC BY-SA 4.0"]}}

C:\Users\fangcheng>
'''


import requests
import datetime, time

class QWEATHER:
    _geo_api = "https://geoapi.qweather.com/v2/"
    _weather_api = "https://api.qweather.com/v7/"
    _weather_api_free = "https://devapi.qweather.com/v7/"

    def __init__(self, api_key):
        self.API_KEY = api_key

    def search(self, service="city", action="lookup", location="北京", coordinate="116.39,39.91", type="scenic", range="cn"):
        api_type = f"{service}/{action}"

        api_params_map = {
            "city/lookup": {"location": location},
            "city/top": {"range": range},
            "poi/lookup": {"location": location, "type": type},
            "poi/range": {"location": coordinate, "type": type}
        }

        if api_type not in api_params_map:
            print("跳过不支持的 API 类型", api_type)
            return None

        # 从 api_params_map 中获取对应参数
        params = api_params_map[api_type]
        url = f"{self._geo_api}{api_type}"
        response = self.http_request_v2(url, method="GET", headers=self.headers(), params=params)
        return response

    def weather(self, service="weather", period="now", locationid=None, coordinate="116.39,39.91", type=None, date=None):
        url = f"{self._weather_api_free}{service}/{period}"
        if service in ["historical"]:
            url = f"{self._weather_api}{service}/{period}"
        params = {"location": locationid if locationid else coordinate}
        if type:
            params['type'] = type
        if date:
            params['date'] = date
        response = self.http_request_v2(url, method="GET", headers=self.headers(), params=params)
        return response

    # 生成 headers 头
    def headers(self, params=None):
        headers = {
            'Content-Type': 'application/json',
            'X-QW-Api-Key': f'{self.API_KEY}'
        }
        return headers

    def http_request_v2(self, url, method="GET", headers={}, params=None, max_retries=2, timeout=3):
        headers = headers or {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36'}
        headers.update(self.headers())
        for attempts in range(1, max_retries + 1):
            try:
                if method == "GET":
                    response = requests.get(url, headers=headers, params=params, timeout=timeout)
                elif method in ("POST", "DELETE"):
                    response = requests.request(method, url, json=params, headers=headers, timeout=timeout)
                response.raise_for_status()
                return response.json()
            except Exception as e:
                print([datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), attempts, url, method, params, headers, repr(e)])
                time.sleep(timeout * attempts)
        return None


if __name__ == '__main__':
    # 使用示例
    api_key = "c863bab7a74d437bae4c9147056a1234" 
    client = QWEATHER(api_key)

    # # GeoAPI
    # services = ["city", "poi"]
    # actiones = ["lookup", "top", "range"]

    # for service in services:    # 遍历servic
        # for action in actiones:    # 遍历action
            # try:
                # print()
                # print(f" - service: {service} action: {action}")
                # response = client.search(service, action)
                # print(response)
            # except Exception as e:
                # print(f"\033[35m异常\033[0m, MSG: {e}")

    # # 城市搜索
    # print()
    # response = client.search(service="city", action="lookup", location="长沙")
    # print(response)
    # locationid = response['location'][0]['id']
    # print(locationid)

    # # 城市天气
    # periods = ["now", "3d", "7d", "10d", "15d", "30d", "24h", "72h", "168h"]
    # periods = ["now", "3d", "7d", "24h"]
    # for period in periods:
        # print()
        # print(f" - period: {period}")
        # response = client.weather(period=period, locationid='101010100')
        # print(response)
    
    # # 分钟级降水
    # response = client.weather(service="minutely", period='5m', coordinate="116.39,39.91")
    # print(response)

    # # 天气灾害预警
    # response = client.weather(service="warning", period='now', locationid='101010100')
    # print(response)
    
    # # 天气指数预报
    # periods = ["1d", "3d"]
    # types = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"]
    # for period in periods:    # 遍历servic
        # for type in types:    # 遍历action
            # print()
            # print(f" - period: {period} type: {type}")
            # response = client.weather(service="indices", period=period, locationid='101010100', type=type)
            # print(response)

    # # 空气质量
    # periods = ["now", "5d"]
    # for period in periods:
        # print()
        # print(f" - period: {period}")
        # response = client.weather(service="air", period=period, locationid='101010100')
        # print(response)

    # # 天文
    # # 日出日落
    # today = datetime.datetime.now().strftime('%Y%m%d')
    # response = client.weather(service="astronomy", period='sun', locationid='101010100', date=today)
    # print(response)
    # # 月升月落和月相
    # response = client.weather(service="astronomy", period='moon', locationid='101010100', date=today)
    # print(response)
 

 

posted @ 2025-03-28 13:43  方倍工作室  阅读(247)  评论(0)    收藏  举报