OpenWeatherMap是一个提供全球天气数据的开放平台,开发者可以通过其提供的API接口,传入城市名称等参数,获取对应地区的实时天气、未来预报等信息,广泛应用于各类天气类应用、生活服务类应用的开发中。

一、准备工作:获取API密钥
在使用OpenWeatherMap API之前,需要先注册账号并获取专属的API密钥,具体步骤如下:
- 访问OpenWeatherMap官网,完成账号注册并登录
- 进入个人控制台,找到API Keys板块,系统会默认生成一个免费的API密钥
- 如果是免费版用户,需要注意接口的调用频率限制,通常每分钟最多调用60次,足够个人开发和小项目使用
二、接口基本说明
通过城市名称获取天气预报的核心接口是当前天气数据接口,基础请求地址为https://api.openweathermap.org/data/2.5/weather,需要传入以下必要参数:
| 参数名 | 说明 | 是否必填 |
|---|---|---|
| q | 城市名称,格式为城市名,国家代码,例如Beijing,cn | 是 |
| appid | 之前获取的API密钥 | 是 |
| units | 温度单位,metric为摄氏度,imperial为华氏度,默认是开尔文 | 否 |
| lang | 返回数据的语言,zh_cn为中文 | 否 |
三、代码示例
1. Python调用示例
使用Python的requests库发送请求,解析返回的JSON数据:
import requests
# 配置参数
api_key = "你的API密钥"
city = "Beijing,cn" # 城市名加国家代码
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric&lang=zh_cn"
# 发送请求
response = requests.get(url)
if response.status_code == 200:
data = response.json()
# 解析天气数据
city_name = data["name"]
weather_desc = data["weather"][0]["description"]
temp = data["main"]["temp"]
humidity = data["main"]["humidity"]
print(f"城市:{city_name}")
print(f"天气:{weather_desc}")
print(f"温度:{temp}℃")
print(f"湿度:{humidity}%")
else:
print(f"请求失败,状态码:{response.status_code}")
2. JavaScript调用示例
前端使用fetch API调用接口获取数据:
const apiKey = "你的API密钥";
const city = "Shanghai,cn";
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric&lang=zh_cn`;
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`请求失败,状态码:${response.status}`);
}
return response.json();
})
.then(data => {
const cityName = data.name;
const weatherDesc = data.weather[0].description;
const temp = data.main.temp;
const humidity = data.main.humidity;
console.log(`城市:${cityName}`);
console.log(`天气:${weatherDesc}`);
console.log(`温度:${temp}℃`);
console.log(`湿度:${humidity}%`);
})
.catch(error => {
console.error("调用出错:", error);
});
3. PHP调用示例
使用PHP的curl扩展发送请求:
<?php
$apiKey = "你的API密钥";
$city = "Guangzhou,cn";
$url = "https://api.openweathermap.org/data/2.5/weather?q={$city}&appid={$apiKey}&units=metric&lang=zh_cn";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
if ($response) {
$data = json_decode($response, true);
$cityName = $data["name"];
$weatherDesc = $data["weather"][0]["description"];
$temp = $data["main"]["temp"];
$humidity = $data["main"]["humidity"];
echo "城市:{$cityName}n";
echo "天气:{$weatherDesc}n";
echo "温度:{$temp}℃n";
echo "湿度:{$humidity}%n";
} else {
echo "请求失败,无法获取数据";
}
?>
四、常见问题处理
- 如果返回404错误,通常是城市名称或者国家代码填写错误,建议检查格式是否正确,国家代码需要使用ISO 3166标准的两位代码
- 如果返回401错误,说明API密钥无效或者没有正确传入,需要检查密钥是否正确,以及请求地址中appid参数是否拼接正确
- 免费版接口不支持HTTPS以外的请求方式,同时不要频繁调用,避免触发频率限制导致接口暂时不可用
注意:实际开发时不要把API密钥直接写在前端代码中,建议通过后端服务转发请求,避免密钥泄露造成不必要的损失。
OpenWeatherMap_API天气预报城市名称查询API调用修改时间:2026-07-22 00:39:27