编写一个python-代码调用api接口的案例
以下是一个调用OpenWeatherMap API接口获取天气信息的Python示例代码:
import requests
# API接口地址和API密钥
api_url = "https://api.openweathermap.org/data/2.5/weather"
api_key = "YOUR_API_KEY"
# 要查询的城市名
city_name = "Beijing"
# 构建请求参数
params = {
"q": city_name,
"appid": api_key,
"units": "metric"
}
# 发送请求
response = requests.get(api_url, params=params)
# 解析响应数据
if response.status_code == 200:
weather_data = response.json()
print(f"城市:{weather_data['name']}")
print(f"天气:{weather_data['weather'][0]['description']}")
print(f"温度:{weather_data['main']['temp']}°C")
print(f"湿度:{weather_data['main']['humidity']}%")
else:
print(f"请求失败:{response.status_code}")
以上代码中,我们首先设置了API接口地址和API密钥,然后指定了要查询的城市名,并构建了请求参数。接着,我们使用requests库发送请求,并根据响应状态码解析响应数据。最后,我们将获取到的天气信息输出到控制台。
原文地址: https://www.cveoy.top/t/topic/q8w 著作权归作者所有。请勿转载和采集!