连接 API 与服务器
Coddy Python 中的 API 课程的第 8 课,共 10 课。
挑战
中等OpenWeatherMap 通常需要 API 密钥,但为了学习,我们会使用一种无需注册的免费替代方案:Open-Meteo API。
向以下地址发送 GET 请求:https://api.open-meteo.com/v1/forecast
使用 params 添加以下参数:
{
"latitude": 52.52,
"longitude": 13.41,
"current_weather": "true"
}将 requests.get() 对象保存到名为 response 的变量中。
使用 response.json() 解析响应,并将其保存到名为 data 的变量中。
通过访问 data["current_weather"]["temperature"] 输出当前温度。
亲手试试
import requests
# Step 1: Send GET request with parameters
response = requests.get(
# Your URL here
params={
# Your parameters here
}
)
# Step 2: Parse JSON response
data = # Your code here
# Step 3: Print current temperature
print("Current temperature:", data["current_weather"]["temperature"], "°C")Python 中的 API中的所有课
自己练习: Python 在线编译器