构建一个天气API集成,可以使用Python中的requests库来发送HTTP请求到天气API,并获取实时的天气数据。以下是一个简单的示例,展示如何使用OpenWeatherMap API来获取天气信息。
步骤:
注册并获取API密钥 :
首先,你需要在 OpenWeatherMap 上注册一个账户,并获取一个免费的API密钥。
安装依赖 :
你需要安装requests库来发送HTTP请求。如果你还没有安装它,可以通过以下命令安装:
pip install requests
编写代码 :
下面是一个简单的Python脚本,它使用OpenWeatherMap API来获取指定城市的天气信息。
import requests
# OpenWeatherMap API的URL和你的API密钥
API_KEY = 'your_api_key_here' # 替换为你的API密钥
BASE_URL = 'http://api.openweathermap.org/data/2.5/weather'
def get_weather(city_name):
# 构建请求参数
params = {
'q': city_name, # 城市名称
'appid': API_KEY, # 你的API密钥
'units': 'metric', # 使用摄氏度(默认是开尔文)
'lang':