如何使用 API 获取天气数据
如何使用 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
: 天气状况 IDmain
: 天气状况描述 (例如: "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
: 城市 IDname
: 城市名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]
- 本文标签: 技术
- 本文链接: https://blog.sandy1029.cloud/article/447
- 版权声明: 本文由nisan原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权