从零实现天气查询功能:三种编程语言的完整接入教程

手把手教你用Python、JavaScript和cURL对接免费天气API,包含错误处理、数据缓存、中文城市名转换等实战技巧。

李伟

全栈开发者,专注于API集成和开发者工具开发,擅长用通俗易懂的方式讲解技术。

15 分钟

准备工作

本教程使用 Open-Meteo 天气API,它完全免费、无需注册、没有调用次数限制。你需要的只是一个能发送HTTP请求的开发环境。

第一步:理解API参数

Open-Meteo天气预报API的核心参数:

  • latitude(必填)— 纬度坐标
  • longitude(必填)— 经度坐标
  • current_weather(可选)— 是否包含当前天气
  • daily(可选)— 需要返回的每日数据字段
  • timezone(可选)— 时区设置

第二种方式:cURL

curl "https://api.open-meteo.com/v1/forecast?latitude=39.9042&longitude=116.4074¤t_weather=true"

第三种方式:Python

import requests

response = requests.get( 'https://api.open-meteo.com/v1/forecast', params={ 'latitude': 39.9042, 'longitude': 116.4074, 'current_weather': 'true' } ) data = response.json() print(data['current_weather']['temperature'])

第四种方式:JavaScript (Node.js)

const response = await fetch(

'https://api.open-meteo.com/v1/forecast?latitude=39.9042&longitude=116.4074¤t_weather=true' ); const data = await response.json(); console.log(data.current_weather.temperature);

错误处理与缓存

在生产环境中,建议:

  • 设置超时时间(推荐5秒)
  • 捕获异常并降级到备用API
  • 实现30分钟本地缓存
  • 将WMO天气代码转换为中文描述