import requests
def call_api(url, params=None):
"""
调用外部API接口的示例函数。
参数:
url (str): API的URL地址。
params (dict, optional): 请求参数,默认为None。
返回:
dict: 响应内容,通常为JSON格式的数据。
"""
try:
response = requests.get(url, params=params)
response.raise_for_status() # 检查请求是否成功
return response.json() # 返回JSON格式的数据
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
return None
# 示例调用
api_url = "https://api.example.com/data"
query_params = {"key1": "value1", "key2": "value2"}
result = call_api(api_url, query_params)
if result:
print("API响应:", result)
else:
print("未能获取到有效响应")
requests库来发送HTTP请求。如果未安装该库,可以通过pip install requests进行安装。call_api函数用于调用API接口,接收两个参数:url和params。requests.get方法发送GET请求,并传递URL和参数。call_api函数,并打印结果。如果你需要调用其他类型的API(如POST请求),可以相应地修改请求方法和其他参数。
上一篇:python调用post接口
下一篇:python导入文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站