### v2.6 API Request Example (Bash) Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/auth.html Demonstrates how to make a request to the v2.6 API using App Key & App Secret authentication. Includes examples with and without query parameters. ```bash curl "https://api.caiyunapp.com/v2.6/{app_key}/{longitude},{latitude}/weather?{query}" \ -H 'x-cy-nonce: {nonce}' \ -H 'x-cy-timestamp: {timestamp}' \ -H 'x-cy-signature: {signature}' ``` ```bash # 无 query 参数 curl "https://api.caiyunapp.com/v2.6/your_app_key/116.3176,39.9760/realtime" \ -H 'x-cy-nonce: 0195c68a-42e7-7243-bff2-ac97a78b837d' \ -H 'x-cy-timestamp: 1742791910' \ -H 'x-cy-signature: your_signature_here' # 有 query 参数 curl "https://api.caiyunapp.com/v2.6/your_app_key/116.3176,39.9760/weather?alert=true&dailysteps=1&hourlysteps=24" \ -H 'x-cy-nonce: 0195c68a-42e7-7243-bff2-ac97a78b837d' \ -H 'x-cy-timestamp: 1742791910' \ -H 'x-cy-signature: your_signature_here' ``` -------------------------------- ### Golang Signature Calculation Example Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/auth.html Example implementation in Golang for calculating the HMAC-SHA256 signature required for API authentication. ```APIDOC ```go package main import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "fmt" "net/http" "net/url" "sort" "strconv" "strings" ) func Sign( appKey string, appSecret string, method string, path string, nonce string, timestamp int64, query map[string]string, ) string { // 1. Sort query parameters alphabetically keys := make([]string, 0, len(query)) for k := range query { keys = append(keys, k) } sort.Strings(keys) // 2. Construct query string (URL encoded) var queryStr strings.Builder for i, k := range keys { if i > 0 { queryStr.WriteString("&") } queryStr.WriteString(url.QueryEscape(k)) queryStr.WriteString("=") queryStr.WriteString(url.QueryEscape(query[k])) } // 3. Construct signature string stringToSign := strings.Join([]string{ method, path, queryStr.String(), appKey, nonce, strconv.FormatInt(timestamp, 10), }, ":") // 4. Calculate signature using HMAC-SHA256 h := hmac.New(sha256.New, []byte(appSecret)) h.Write([]byte(stringToSign)) // 5. URL-safe Base64 encoding signature := base64.URLEncoding.EncodeToString(h.Sum(nil)) return signature } func main() { appKey := "your_app_key" appSecret := "your_app_secret" method := http.MethodGet path := "/v2.6/your_app_key/116.3176,39.9760/weather" query := map[string]string{ "alert": "true", "dailysteps": "1", "hourlysteps": "24", } nonce := "0195c68a-42e7-7243-bff2-ac97a78b837d" timestamp := int64(1742791910) signature := Sign(appKey, appSecret, method, path, nonce, timestamp, query) fmt.Println("Signature:", signature) // Signature: KfHsk3z2XfX6Yxox4Uf_VgyM0wHk6bWEyRqZ9QOJUYw= } ``` ``` -------------------------------- ### Python Signature Calculation Example Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/auth.html Example implementation in Python for calculating the HMAC-SHA256 signature required for API authentication. ```APIDOC ```python import hmac import hashlib import base64 import urllib.parse from typing import Dict def sign( app_key: str, app_secret: str, method: str, path: str, nonce: str, timestamp: str, query: Dict[str, str], ) -> str: # 1. Sort query parameters alphabetically sorted_keys = sorted(query.keys()) # 2. Construct query string (URL encoded, aligned with Golang's url.QueryEscape) query_parts = [] for k in sorted_keys: encoded_key = urllib.parse.quote_plus(k, safe="") encoded_value = urllib.parse.quote_plus(query[k], safe="") query_parts.append(f"{encoded_key}={encoded_value}") query_str = "&".join(query_parts) # 3. Construct signature string string_to_sign = ":".join([method, path, query_str, app_key, nonce, timestamp]) # 4. Calculate signature using HMAC-SHA256 h = hmac.new(app_secret.encode("utf-8"), string_to_sign.encode("utf-8"), hashlib.sha256) # 5. URL-safe Base64 encoding signature = base64.urlsafe_b64encode(h.digest()).decode("utf-8") return signature ``` ``` -------------------------------- ### Requesting Realtime Weather Data with Alerts Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/5-alert.html To include alert data in your request, append the `alert=true` parameter to any weather data endpoint. This example shows how to add it to a realtime data request. ```bash curl "https://api.caiyunapp.com/v2.6/TAkhjf8d1nlSlspN/116.3176,39.9760/realtime?alert=true" ``` -------------------------------- ### Realtime Weather Data (Token Auth - Not Recommended) Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/auth.html This example shows how to fetch real-time weather data using the Token authentication method. It is strongly advised to use App Key & App Secret authentication instead due to security risks associated with exposing tokens in URLs. ```APIDOC ## GET /v2.6/{token}/{longitude},{latitude}/realtime ### Description Fetches real-time weather data for a specified location using Token authentication. This method is not recommended due to security risks. ### Method GET ### Endpoint /v2.6/{token}/{longitude},{latitude}/realtime ### Parameters #### Path Parameters - **token** (string) - Required - Your authentication token. - **longitude** (number) - Required - The longitude coordinate of the location. - **latitude** (number) - Required - The latitude coordinate of the location. ### Request Example ```bash curl "https://api.caiyunapp.com/v2.6/TAkhjf8d1nlSlspN/101.6656,39.2072/realtime" ``` ### Response (Response schema not provided in source) ``` -------------------------------- ### Get Realtime Weather Data Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/1-realtime.html Fetch current weather conditions for a given latitude and longitude. ```APIDOC ## GET /v2.6/{token}/{location}/realtime ### Description Retrieves the current weather conditions for a specified location. ### Method GET ### Endpoint `/v2.6/{token}/{location}/realtime` ### Parameters #### Path Parameters - **token** (string) - Required - Your API token. - **location** (string) - Required - The latitude and longitude of the location, separated by a comma (e.g., `101.6656,39.2072`). ### Request Example ```bash curl "https://api.caiyunapp.com/v2.6/TAkhjf8d1nlSlspN/101.6656,39.2072/realtime" ``` ### Response #### Success Response (200) - **status** (string) - The status of the response ('ok' or 'error'). - **api_version** (string) - The version of the API used. - **api_status** (string) - The status of the API service. - **lang** (string) - The language of the returned data. - **unit** (string) - The unit system used for measurements ('metric' or 'us'). - **tzshift** (integer) - The timezone offset in seconds. - **timezone** (string) - The IANA timezone name. - **server_time** (integer) - The server's current time as a Unix timestamp. - **location** (array) - The requested location coordinates [longitude, latitude]. - **result** (object) - Contains the real-time weather data. - **realtime** (object) - Object containing detailed real-time weather information. - **temperature** (number) - Temperature at 2 meters above ground (in Celsius or Fahrenheit depending on the unit). - **humidity** (number) - Relative humidity at 2 meters above ground (0.0-1.0). - **cloudrate** (number) - Total cloud cover (0.0-1.0). - **skycon** (string) - Sky condition (e.g., 'CLEAR_DAY', 'PARTLY_CLOUDY_NIGHT'). - **visibility** (number) - Horizontal visibility at ground level (in km or miles). - **dswrf** (number) - Downward short-wave radiation flux (W/M2). - **wind** (object) - Wind information. - **speed** (number) - Wind speed at 10 meters above ground (in m/s or mph). - **direction** (number) - Wind direction at 10 meters above ground (degrees). - **pressure** (number) - Barometric pressure at ground level (in Pa). - **apparent_temperature** (number) - Feels-like temperature (in Celsius or Fahrenheit). - **precipitation** (object) - Precipitation information. - **local** (object) - Local precipitation data. - **status** (string) - Status of local precipitation data. - **datasource** (string) - The data source for local precipitation. - **intensity** (number) - Local precipitation intensity (mm/hour). - **nearest** (object) - Nearest precipitation data. - **status** (string) - Status of nearest precipitation data. - **distance** (integer) - Distance to the nearest precipitation (in meters). - **intensity** (number) - Intensity of precipitation at the nearest location (mm/hour). - **air_quality** (object) - Air quality information. - **pm25** (number) - PM2.5 concentration (μg/m3). - **pm10** (number) - PM10 concentration (μg/m3). - **o3** (number) - Ozone concentration (μg/m3). - **so2** (number) - Sulfur dioxide concentration (μg/m3). - **no2** (number) - Nitrogen dioxide concentration (μg/m3). - **co** (number) - Carbon monoxide concentration (mg/m3). - **aqi** (object) - Air Quality Index. - **chn** (integer) - Chinese AQI value. - **usa** (integer) - US AQI value. - **description** (object) - Textual description of air quality. - **chn** (string) - Chinese description. - **usa** (string) - US description. - **life_index** (object) - Life index information. - **ultraviolet** (object) - Ultraviolet index. - **index** (integer) - Ultraviolet index value. - **desc** (string) - Description of the ultraviolet level. - **comfort** (object) - Comfort index. - **index** (integer) - Comfort index value. - **desc** (string) - Description of the comfort level. - **primary** (integer) - Indicates if this is the primary result (usually 0). #### Response Example ```json { "status": "ok", "api_version": "v2.6", "api_status": "active", "lang": "zh_CN", "unit": "metric", "tzshift": 28800, "timezone": "Asia/Shanghai", "server_time": 1640745758, "location": [39.2072, 101.6656], "result": { "realtime": { "status": "ok", "temperature": -7, "humidity": 0.58, "cloudrate": 0, "skycon": "CLEAR_DAY", "visibility": 7.8, "dswrf": 47.7, "wind": { "speed": 1.8, "direction": 22 }, "pressure": 85583.47, "apparent_temperature": -9.9, "precipitation": { "local": { "status": "ok", "datasource": "radar", "intensity": 0 }, "nearest": { "status": "ok", "distance": 10000, "intensity": 0 } }, "air_quality": { "pm25": 45, "pm10": 49, "o3": 6, "so2": 8, "no2": 42, "co": 1.1, "aqi": { "chn": 63, "usa": 124 }, "description": { "chn": "良", "usa": "轻度污染" } }, "life_index": { "ultraviolet": { "index": 3, "desc": "弱" }, "comfort": { "index": 12, "desc": "湿冷" } } }, "primary": 0 } } ``` ``` -------------------------------- ### Requesting Alert Data Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/5-alert.html To obtain weather alert data, append `alert=true` to any v2.6 weather data request. This example shows how to request alert data along with real-time weather information. ```APIDOC ## Request Alert Data ### Description Append `alert=true` to any v2.6 weather data endpoint to include alert information in the response. ### Method GET ### Endpoint `/v2.6/{token}/{longitude},{latitude}/realtime?alert=true` ### Parameters #### Query Parameters - **alert** (boolean) - Required - Set to `true` to include alert data. ### Request Example ```bash curl "https://api.caiyunapp.com/v2.6/TAkhjf8d1nlSlspN/116.3176,39.9760/realtime?alert=true" ``` ### Response #### Success Response (200) - **alert** (object) - Contains detailed weather alert information. - **status** (string) - The status of the alert information (e.g., "ok"). - **content** (array) - An array of alert objects, each containing details like province, status, code, description, regionId, county, pubtimestamp, latlon, city, alertId, title, adcode, source, and location. - **adcodes** (array) - An array of objects, each containing `adcode` (area code) and `name` (area name) for administrative divisions. ### Response Example ```json { "status": "ok", "api_version": "v2.6", "api_status": "alpha", "lang": "zh_CN", "unit": "metric", "tzshift": 28800, "timezone": "Asia/Shanghai", "server_time": 1640759880, "location": [39.976, 116.3176], "result": { "alert": { "status": "ok", "content": [ { "province": "北京市", "status": "预警中", "code": "0501", "description": "海淀区气象台29日07时25分发布大风蓝色预警,预计,当前至29日16时,海淀区将有3、4级偏北风,阵风6、7级,请注意防范。", "regionId": "101010200", "county": "无", "pubtimestamp": 1640733900, "latlon": [39.959912, 116.298056], "city": "海淀区", "alertId": "11010841600000_20211229072633", "title": "海淀区气象台发布大风蓝色预警[IV/一般]", "adcode": "110108", "source": "国家预警信息发布中心", "location": "北京市海淀区", "request_status": "ok" } ], "adcodes": [ { "adcode": 110000, "name": "北京市" }, { "adcode": 110108, "name": "海淀区" } ] }, "realtime": {}, "primary": 0 } } ``` ``` -------------------------------- ### Get Daily Weather Forecast Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/4-daily.html Retrieve the daily weather forecast for a specific geographic location. You can control the number of days for the forecast using the `dailysteps` parameter. ```APIDOC ## GET /v2.6/{key}/{location}/daily ### Description Retrieves the daily weather forecast for a specified location. ### Method GET ### Endpoint `/v2.6/{key}/{location}/daily` ### Parameters #### Path Parameters - **key** (string) - Required - Your API key. - **location** (string) - Required - The longitude and latitude of the location (e.g., `101.6656,39.2072`). #### Query Parameters - **dailysteps** (integer) - Optional - Controls the number of days of data to return. Accepted values are between 1 and 15. ### Request Example ```bash curl "https://api.caiyunapp.com/v2.6/TAkhjf8d1nlSlspN/101.6656,39.2072/daily?dailysteps=1" ``` ### Response #### Success Response (200) - **status** (string) - The status of the request (e.g., "ok"). - **api_version** (string) - The API version used. - **api_status** (string) - The status of the API (e.g., "alpha"). - **lang** (string) - The language of the response. - **unit** (string) - The unit system used for the data (e.g., "metric"). - **tzshift** (integer) - The timezone offset in seconds. - **timezone** (string) - The IANA timezone name. - **server_time** (integer) - The server's current time as a Unix timestamp. - **location** (array) - An array containing the latitude and longitude of the requested location. - **result** (object) - An object containing the daily weather data. - **daily** (object) - Contains detailed daily weather information. - **status** (string) - The status of the daily data retrieval. - **astro** (array) - Array of astronomical data (sunrise, sunset) for each day. - **precipitation_08h_20h** (array) - Daytime precipitation data. - **precipitation_20h_32h** (array) - Nighttime precipitation data. - **precipitation** (array) - Full day precipitation data. - **temperature** (array) - Full day temperature data. - **temperature_08h_20h** (array) - Daytime temperature data. - **temperature_20h_32h** (array) - Nighttime temperature data. - **wind** (array) - Full day wind data. - **wind_08h_20h** (array) - Daytime wind data. - **wind_20h_32h** (array) - Nighttime wind data. - **humidity** (array) - Relative humidity data. - **cloudrate** (array) - Cloud cover data. - **pressure** (array) - Barometric pressure data. - **visibility** (array) - Visibility data. - **dswrf** (array) - Downward shortwave radiation flux data. - **air_quality** (object) - Air quality information. - **aqi** (array) - Air Quality Index data. - **pm25** (array) - PM2.5 concentration data. - **skycon** (array) - Sky condition data. #### Response Example ```json { "status": "ok", "api_version": "v2.6", "api_status": "alpha", "lang": "zh_CN", "unit": "metric", "tzshift": 28800, "timezone": "Asia/Shanghai", "server_time": 1653552787, "location": [ 39.2072, 101.6656 ], "result": { "daily": { "status": "ok", "astro": [ { "date": "2022-05-26T00:00+08:00", "sunrise": { "time": "05:51" }, "sunset": { "time": "20:28" } } ], "precipitation_08h_20h": [ { "date": "2022-05-26T00:00+08:00", "max": 0, "min": 0, "avg": 0, "probability": 0 } ], "precipitation_20h_32h": [ { "date": "2022-05-26T00:00+08:00", "max": 0, "min": 0, "avg": 0, "probability": 0 } ], "precipitation": [ { "date": "2022-05-26T00:00+08:00", "max": 0, "min": 0, "avg": 0, "probability": 0 } ], "temperature": [ { "date": "2022-05-26T00:00+08:00", "max": 27, "min": 18, "avg": 23.75 } ], "temperature_08h_20h": [ { "date": "2022-05-26T00:00+08:00", "max": 27, "min": 18, "avg": 24.57 } ], "temperature_20h_32h": [ { "date": "2022-05-26T00:00+08:00", "max": 24.8, "min": 18, "avg": 20.02 } ], "wind": [ { "date": "2022-05-26T00:00+08:00", "max": { "speed": 28.24, "direction": 122.62 }, "min": { "speed": 9, "direction": 104 }, "avg": { "speed": 21.61, "direction": 118.02 } } ], "wind_08h_20h": [ { "date": "2022-05-26T00:00+08:00", "max": { "speed": 28.24, "direction": 122.62 }, "min": { "speed": 9, "direction": 104 }, "avg": { "speed": 22.74, "direction": 115.78 } } ], "wind_20h_32h": [ { "date": "2022-05-26T00:00+08:00", "max": { "speed": 22.39, "direction": 97.46 }, "min": { "speed": 9.73, "direction": 125.93 }, "avg": { "speed": 16, "direction": 121.62 } } ], "humidity": [ { "date": "2022-05-26T00:00+08:00", "max": 0.18, "min": 0.08, "avg": 0.09 } ], "cloudrate": [ { "date": "2022-05-26T00:00+08:00", "max": 1, "min": 0, "avg": 0.75 } ], "pressure": [ { "date": "2022-05-26T00:00+08:00", "max": 84500.84, "min": 83940.84, "avg": 83991.97 } ], "visibility": [ { "date": "2022-05-26T00:00+08:00", "max": 25, "min": 24.13, "avg": 25 } ], "dswrf": [ { "date": "2022-05-26T00:00+08:00", "max": 741.9, "min": 0, "avg": 368.6 } ], "air_quality": { "aqi": [ { "date": "2022-05-26T00:00+08:00", "max": { "chn": 183, "usa": 160 }, "avg": { "chn": 29, "usa": 57 }, "min": { "chn": 20, "usa": 42 } } ], "pm25": [ { "date": "2022-05-26T00:00+08:00", "max": 74, "avg": 15, "min": 10 } ] }, "skycon": [ { "date": "2022-05-26T00:00+08:00" } ] } } } ``` -------------------------------- ### App Key & App Secret Authentication Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/auth.html This section covers the App Key & App Secret authentication method for the v2.6 API. It includes request examples, parameter explanations, and the signature calculation process. ```APIDOC ## App Key & App Secret Authentication ### Request Example ```bash curl "https://api.caiyunapp.com/v2.6/{app_key}/{longitude},{latitude}/weather?{query}" \ -H 'x-cy-nonce: {nonce}' \ -H 'x-cy-timestamp: {timestamp}' \ -H 'x-cy-signature: {signature}' ``` **Actual Example**: ```bash # Without query parameters curl "https://api.caiyunapp.com/v2.6/your_app_key/116.3176,39.9760/realtime" \ -H 'x-cy-nonce: 0195c68a-42e7-7243-bff2-ac97a78b837d' \ -H 'x-cy-timestamp: 1742791910' \ -H 'x-cy-signature: your_signature_here' # With query parameters curl "https://api.caiyunapp.com/v2.6/your_app_key/116.3176,39.9760/weather?alert=true&dailysteps=1&hourlysteps=24" \ -H 'x-cy-nonce: 0195c68a-42e7-7243-bff2-ac97a78b837d' \ -H 'x-cy-timestamp: 1742791910' \ -H 'x-cy-signature: your_signature_here' ``` ### Request Description 1. **URL Path Parameters** * `app_key`: Authentication credential obtained from the open platform (placed in the URL path, replacing the original token). * `longitude`: Longitude. * `latitude`: Latitude. 2. **Authentication Headers** * `x-cy-nonce`: Random string, length requirement 16-40 characters, UUID is recommended, must be unique for each request. * `x-cy-timestamp`: Timestamp of the request time (outdated timestamps may be rejected). * `x-cy-signature`: Signature, calculation method described below. 3. **Request Parameters** * `method`: HTTP request method (currently only GET is supported). * `path`: API request path (including `app_key`). * `query`: Optional query parameters (e.g., `alert`, `dailysteps`, `hourlysteps`). ### Signature Calculation 1. **Parameter Sorting** (if query parameters exist) * Sort query parameters alphabetically. * Example: `hourlysteps=24&dailysteps=1&alert=true` → `alert=true&dailysteps=1&hourlysteps=24` 2. **Construct Signature String** * Concatenate in the following format: `{method}:{path}:{query}:{app_key}:{nonce}:{timestamp}` * Example without query parameters: `GET:/v2.6/your_app_key/116.3176,39.9760/realtime::your_app_key:0195c68a-42e7-7243-bff2-ac97a78b837d:1742791910` * Example with query parameters: `GET:/v2.6/your_app_key/116.3176,39.9760/weather:alert=true&dailysteps=1&hourlysteps=24:your_app_key:0195c68a-42e7-7243-bff2-ac97a78b837d:1742791910` 3. **Calculate Hash Value** * Perform HMAC-SHA256 hash calculation on the signature string, using `app_secret` as the key. * Example: `hmac_sha256(stringToSign, app_secret)` 4. **Generate Signature** * Encode the hash value using URL Safe Base64. * Example: `base64(hmac_sha256_result)` ``` -------------------------------- ### Construct Token Auth URL (v2.6) Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/auth.html Use this format to construct API requests with token authentication in v2.6. Tokens are directly included in the URL path. This method is not recommended due to security risks. ```bash curl "https://api.caiyunapp.com/v2.6/{token}/{longitude},{latitude}/realtime" ``` ```bash curl "https://api.caiyunapp.com/v2.6/TAkhjf8d1nlSlspN/101.6656,39.2072/realtime" ``` -------------------------------- ### API Error Response Format Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/tables/errors.html This is an example of the JSON structure returned when an API request fails. Always check the HTTP status code to confirm successful data retrieval. ```json { "status": "failed", "error": "token is invalid", "api_version": "2.6" } ``` -------------------------------- ### 请求分钟级预报数据 Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/2-minutely.html 使用此 cURL 命令请求指定经纬度的分钟级天气预报。请替换 API 密钥和坐标。 ```bash curl "https://api.caiyunapp.com/v2.6/TAkhjf8d1nlSlspN/101.6656,39.2072/minutely" ``` -------------------------------- ### Request Daily Forecast Data Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/4-daily.html Use this cURL command to request daily weather forecast data. The `dailysteps` parameter controls the number of forecast days, with a range of 1 to 15. ```bash curl "https://api.caiyunapp.com/v2.6/TAkhjf8d1nlSlspN/101.6656,39.2072/daily?dailysteps=1" ``` -------------------------------- ### Fetch Comprehensive Weather Data Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/6-weather.html Use this cURL command to request a package of weather data including alerts, minutely, hourly, and daily forecasts. Ensure you replace 'TAkhjf8d1nlSlspN' with your actual API key and adjust the coordinates and parameters as needed. ```bash curl "https://api.caiyunapp.com/v2.6/TAkhjf8d1nlSlspN/116.3176,39.9760/weather?alert=true&dailysteps=1&hourlysteps=24" ``` -------------------------------- ### Sign Request with App Key & App Secret (Python) Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/auth.html Provides a Python implementation for generating the signature required for v2.6 API requests. It mirrors the Golang logic for parameter sorting, string construction, and HMAC-SHA256 hashing with URL-safe Base64 encoding. ```python import hmac import hashlib import base64 import urllib.parse from typing import Dict def sign( app_key: str, app_secret: str, method: str, path: str, nonce: str, timestamp: str, query: Dict[str, str], ) -> str: # 1. 对 query 参数按字母顺序排序 sorted_keys = sorted(query.keys()) # 2. 构建 query 字符串(URL 编码,与 Golang 的 url.QueryEscape 对齐) query_parts = [] for k in sorted_keys: encoded_key = urllib.parse.quote_plus(k, safe="") encoded_value = urllib.parse.quote_plus(query[k], safe="") query_parts.append(f"{encoded_key}={encoded_value}") query_str = "&".join(query_parts) # 3. 构建签名字符串 string_to_sign = ":".join([method, path, query_str, app_key, nonce, timestamp]) # 4. 使用 HMAC-SHA256 计算签名 h = hmac.new(app_secret.encode("utf-8"), string_to_sign.encode("utf-8"), hashlib.sha256) # 5. Base64 编码(URL 安全) signature = base64.urlsafe_b64encode(h.digest()).decode("utf-8") return signature ``` -------------------------------- ### Sign Request with App Key & App Secret (Golang) Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/auth.html Implements the signature calculation for v2.6 API requests in Golang. It sorts query parameters, builds the signature string, computes HMAC-SHA256, and encodes the result using URL-safe Base64. ```go package main import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "fmt" "net/http" "net/url" "sort" "strconv" "strings" ) func Sign( appKey string, appSecret string, method string, path string, nonce string, timestamp int64, query map[string]string, ) string { // 1. 对 query 参数按字母顺序排序 keys := make([]string, 0, len(query)) for k := range query { keys = append(keys, k) } sort.Strings(keys) // 2. 构建 query 字符串(URL 编码) var queryStr strings.Builder for i, k := range keys { if i > 0 { queryStr.WriteString("&") } queryStr.WriteString(url.QueryEscape(k)) queryStr.WriteString("=") queryStr.WriteString(url.QueryEscape(query[k])) } // 3. 构建签名字符串 stringToSign := strings.Join([]string{ method, path, queryStr.String(), appKey, nonce, strconv.FormatInt(timestamp, 10), }, ":") // 4. 使用 HMAC-SHA256 计算签名 h := hmac.New(sha256.New, []byte(appSecret)) h.Write([]byte(stringToSign)) // 5. Base64 编码(URL 安全) signature := base64.URLEncoding.EncodeToString(h.Sum(nil)) return signature } func main() { appKey := "your_app_key" appSecret := "your_app_secret" method := http.MethodGet path := "/v2.6/your_app_key/116.3176,39.9760/weather" query := map[string]string{ "alert": "true", "dailysteps": "1", "hourlysteps": "24", } nonce := "0195c68a-42e7-7243-bff2-ac97a78b837d" timestamp := int64(1742791910) signature := Sign(appKey, appSecret, method, path, nonce, timestamp, query) fmt.Println("Signature:", signature) // Signature: KfHsk3z2XfX6Yxox4Uf_VgyM0wHk6bWEyRqZ9QOJUYw= } ``` -------------------------------- ### Comprehensive Weather Data Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/6-weather.html This endpoint provides a comprehensive set of weather data, including real-time conditions, minute-by-minute precipitation forecasts, hourly forecasts, daily forecasts, and weather alerts. It allows for flexible data retrieval by specifying which data types to include. ```APIDOC ## GET /v2.6/{appCode}/{location}/weather ### Description Fetches comprehensive weather data including realtime, minutely, hourly, daily, and alert information for a specified location. ### Method GET ### Endpoint /v2.6/{appCode}/{location}/weather ### Parameters #### Path Parameters - **appCode** (string) - Required - Your unique application code. - **location** (string) - Required - The geographical coordinates in the format 'longitude,latitude'. #### Query Parameters - **alert** (boolean) - Optional - Whether to include weather alerts. Defaults to false. - **dailysteps** (integer) - Optional - The number of days for the daily forecast. Defaults to 1. - **hourlysteps** (integer) - Optional - The number of hours for the hourly forecast. Defaults to 24. ### Request Example ```bash curl "https://api.caiyunapp.com/v2.6/TAkhjf8d1nlSlspN/116.3176,39.9760/weather?alert=true&dailysteps=1&hourlysteps=24" ``` ### Response #### Success Response (200) - **status** (string) - The status of the API request (e.g., "ok"). - **api_version** (string) - The version of the API used. - **api_status** (string) - The status of the API (e.g., "alpha"). - **lang** (string) - The language of the response. - **unit** (string) - The unit system used for the data (e.g., "metric"). - **tzshift** (integer) - The timezone offset in seconds. - **timezone** (string) - The IANA timezone name. - **server_time** (integer) - The server's current time as a Unix timestamp. - **location** (array) - The geographical coordinates [latitude, longitude]. - **result** (object) - Contains the weather data. - **alert** (object) - Weather alert information. - **realtime** (object) - Real-time weather data. - **minutely** (object) - Minute-by-minute precipitation data. - **hourly** (object) - Hourly forecast data. - **daily** (object) - Daily forecast data. - **primary** (integer) - Indicates the primary data source. - **forecast_keypoint** (string) - A key weather change point for the short-term future (e.g., next 2 hours). #### Response Example ```json { "status": "ok", "api_version": "v2.6", "api_status": "alpha", "lang": "zh_CN", "unit": "metric", "tzshift": 28800, "timezone": "Asia/Shanghai", "server_time": 1640758065, "location": [39.976, 116.3176], "result": { "alert": {}, "realtime": {}, "minutely": {}, "hourly": {}, "daily": {}, "primary": 0, "forecast_keypoint": "未来两小时不会下雨,放心出门吧" } } ``` ### Field Descriptions - **`result.hourly.description`**: Description of weather changes over the next 24 hours, consistent with the standalone hourly API. - **`result.forecast_keypoint`**: Key weather changes for the short-term future (next 2 hours), suitable for prominent UI display or 'upcoming event' notifications. ``` -------------------------------- ### Request Hourly Forecast Data Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/3-hourly.html Use this cURL command to request hourly forecast data for a specific location. The `hourlysteps` parameter controls the number of hours of data to retrieve. ```bash curl "https://api.caiyunapp.com/v2.6/TAkhjf8d1nlSlspN/101.6656,39.2072/hourly?hourlysteps=1" ``` -------------------------------- ### Minute-level Precipitation Forecast Source: https://docs.caiyunapp.com/weather-api/v2/v2.6/2-minutely.html This endpoint provides a minute-by-minute forecast of precipitation intensity and probability for the next two hours. It also includes a textual description of the forecast. ```APIDOC ## GET /v2.6/{token}/{location}/minutely ### Description Retrieves minute-level precipitation forecast data for a specified location for the next two hours. ### Method GET ### Endpoint https://api.caiyunapp.com/v2.6/{token}/{longitude},{latitude}/minutely ### Parameters #### Path Parameters - **token** (string) - Required - Your API token. - **longitude** (number) - Required - The longitude of the location. - **latitude** (number) - Required - The latitude of the location. ### Request Example ```bash curl "https://api.caiyunapp.com/v2.6/TAkhjf8d1nlSlspN/101.6656,39.2072/minutely" ``` ### Response #### Success Response (200) - **status** (string) - Overall status of the API response. - **api_version** (string) - The version of the API used. - **api_status** (string) - The status of the API service. - **lang** (string) - The language of the response. - **unit** (string) - The unit system used for the forecast (e.g., 'metric'). - **tzshift** (integer) - Timezone offset in seconds. - **timezone** (string) - The timezone of the location. - **server_time** (integer) - The server's current time as a Unix timestamp. - **location** (array) - The requested [longitude, latitude]. - **result** (object) - Contains the forecast details. - **result.minutely** (object) - Minute-level precipitation forecast details. - **status** (string) - Status of the minute-level forecast. - **datasource** (string) - The data source (e.g., 'radar'). - **precipitation_2h** (array) - Array of radar precipitation intensity for the next 2 hours, per minute. - **precipitation** (array) - Array of radar precipitation intensity for the next 1 hour, per minute. - **probability** (array) - Array of precipitation probability for the next two hours, per half-hour (0-1). - **description** (string) - Textual description of the precipitation forecast for the next 2 hours. - **primary** (integer) - Primary forecast indicator. - **forecast_keypoint** (string) - Key point summary of the forecast. #### Response Example ```json { "status": "ok", "api_version": "v2.6", "api_status": "active", "lang": "zh_CN", "unit": "metric", "tzshift": 28800, "timezone": "Asia/Shanghai", "server_time": 1640747476, "location": [39.2072, 101.6656], "result": { "minutely": { "status": "ok", "datasource": "radar", "precipitation_2h": [ 0, 0, 0 ], "precipitation": [ 0, 0, 0 ], "probability": [0, 0, 0, 0], "description": "未来两小时不会下雪,放心出门吧" }, "primary": 0, "forecast_keypoint": "未来两小时不会下雪,放心出门吧" } } ``` ```