历史天气天气预测实时天气海洋天气 天气

Weatherstack

Weatherstack 是一款提供全球实时、历史和预测天气数据的API服务,以轻量级JSON格式返回准确的气象信息,支持数百万个地点查询。

查看官方文档 ↗

接入教程

1. 访问Weatherstack官网注册账号获取API密钥。2. 使用提供的API端点(如`http://api.weatherstack.com/current`)进行HTTP请求。3. 在请求参数中指定`access_key`和查询地点(如`query=New York`)。4. 解析返回的JSON数据以获取天气信息。

获取当前天气数据

python
import requests

api_key = 'YOUR_API_KEY'
city = 'Beijing'
url = f'https://api.weatherstack.com/current?access_key={api_key}&query={city}'

response = requests.get(url)
data = response.json()

if response.status_code == 200:
    print(f"温度: {data['current']['temperature']}°C")
    print(f"天气描述: {data['current']['weather_descriptions'][0]}")
else:
    print(f"请求失败: {data.get('error', 'Unknown error')}")

查询历史天气

php
<?php

$api_key = 'YOUR_API_KEY';
$city = 'Shanghai';
$date = '2023-10-01';
$url = "https://api.weatherstack.com/historical?access_key={$api_key}&query={$city}&historical_date={$date}";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);

if (isset($data['historical'])) {
    echo "历史温度: " . $data['historical'][$date]['avgtemp'] . "°C\n";
} else {
    echo "错误: " . ($data['error']['info'] ?? '未知错误') . "\n";
}

?>

使用Fetch获取天气预报

javascript
const apiKey = 'YOUR_API_KEY';
const city = 'Guangzhou';
const url = `https://api.weatherstack.com/forecast?access_key=${apiKey}&query=${city}&forecast_days=3`;

fetch(url)
  .then(response => response.json())
  .then(data => {
    if (data.current) {
      console.log(`当前温度: ${data.current.temperature}°C`);
      console.log(`天气预报: ${data.forecast[Object.keys(data.forecast)[0]].avgtemp}°C 平均温度`);
    } else {
      console.error('错误:', data.error?.info || '未知错误');
    }
  })
  .catch(error => console.error('请求失败:', error));

常见问题

Weatherstack API的免费套餐有哪些限制?

免费套餐每月提供1000次请求额度,仅支持当前天气查询,不包含历史数据和天气预报功能,且每小时限速100次请求。

如何解决API返回"invalid_access_key"错误?

请检查API密钥是否正确输入,确保没有多余空格。如果确认密钥正确但仍报错,可能是账户未激活或套餐已过期,请登录官网账户页面核实状态。

API支持哪些查询格式的地点参数?

支持城市名称(如"Beijing")、邮政编码(如"100101")、经纬度坐标(如"39.9042,116.4074")和IP地址(如"134.201.250.155")等多种查询格式。

相似接口推荐

Amazon Forecast 查询服务

该API提供创建和管理Amazon Forecast资源的接口。它让开发者能够使用亚马逊的预测服务,轻松构建和管理预测模型。

待确认
Amazon Forecast Service

该API提供创建和管理Amazon Forecast资源的接口。Amazon Forecast是一项基于机器学习的预测服务,可生成准确的时间序列预测。

待确认
Marketstack股票市场数据API

提供实时、盘中及历史股票市场数据的REST API服务,涵盖全球30,000+股票代码,同时新增EDGAR文件端点用于获取SEC公司申报文件。支持JSON格式响应,提供免费计划。

免费
eBird鸟类观测数据API

康奈尔鸟类学实验室提供的全球鸟类观测数据接口,支持查询特定区域近期或显著的鸟类观察记录

免费