原创

如何使用 API 获取天气数据

温馨提示:
本文最后更新于 2024年07月25日,已超过 251 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

如何使用 API 获取天气数据

1. 简介

本文档介绍如何使用 Weather API 获取实时天气数据。

2. API 概述

  • API 地址: https://api.weather.example.com/v1/weather
  • 请求方法: GET
  • 请求参数:
    • q: 城市名或经纬度坐标 (例如: "London" 或 "51.5074,0.1278")
    • appid: API 密钥 (从开发者网站获取)
    • units: 温度单位 (可选, 默认摄氏度, 可选值: "metric", "imperial")
    • lang: 语言 (可选, 默认英语, 可选值: "en", "zh-CN", "es" 等)

3. 请求示例

获取伦敦的实时天气数据:

bash curl "https://api.weather.example.com/v1/weather?q=London&appid=YOUR_API_KEY&units=metric&lang=en"

4. 响应格式

API 返回 JSON 格式的数据,包含以下字段:

  • coord: 城市坐标
  • weather: 天气信息
    • id: 天气状况 ID
    • main: 天气状况描述 (例如: "Clouds", "Rain")
    • description: 详细天气描述 (例如: "scattered clouds", "light rain")
    • icon: 天气图标 ID
  • base: 数据来源
  • main: 主要天气数据
    • temp: 温度
    • feels_like: 体感温度
    • temp_min: 最低温度
    • temp_max: 最高温度
    • pressure: 气压
    • humidity: 湿度
  • visibility: 能见度
  • wind: 风速和方向
    • speed: 风速
    • deg: 风向
  • clouds: 云量
    • all: 云量百分比
  • dt: 数据更新时间
  • sys: 日出日落时间
    • sunrise: 日出时间
    • sunset: 日落时间
  • timezone: 时区偏移量
  • id: 城市 ID
  • name: 城市名
  • cod: 请求状态码

5. 示例代码

以下示例代码使用 Python 获取天气数据:

```python import requests

api_key = "YOUR_API_KEY" city = "London" units = "metric"

url = f"https://api.weather.example.com/v1/weather?q={city}&appid={api_key}&units={units}"

response = requests.get(url)

if response.status_code == 200: data = response.json() temperature = data["main"]["temp"] description = data["weather"][0]["description"] print(f"The temperature in {city} is {temperature}°C, with {description}.") else: print("Error:", response.status_code) ```

6. 注意事项

  • 请勿将 API 密钥公开,以免被滥用。
  • API 请求频率有限制,请避免过频请求。
  • API 数据仅供参考,不保证其准确性。

7. 联系方式

如果您有任何问题,请访问开发者网站或发送邮件至 [email protected]

正文到此结束