检查API密钥、URL和参数是否正确,并确保网络连接正常。同时,可以查看API返回的错误信息以获取更多指示。代码示例:
import requests
API_KEY = "your_api_key"
URL = "https://api.example.com/get_data"
# 设置请求参数
params = {"param1": "value1", "param2": "value2"}
# 发起API请求
response = requests.get(URL, params=params, headers={"Authorization": f"Bearer {API_KEY}"})
# 检查HTTP状态码是否为200
if response.status_code == 200:
# 解析API返回的数据
data = response.json()
print(data)
else:
# 打印API返回的错误信息
print(response.text)