Python如何发送携带前序请求返回唯一ID的多个API请求
多API串行请求实现方案(Python 环境)
前置依赖
首先安装所需第三方库:pip install pandas requests
完整实现代码
import pandas as pd import requests import json # 仅内网自签名证书场景需要,用于忽略证书告警 import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # 第一个请求地址,注意去掉原URL中https://后的多余空格 first_url = "https://10.200.35.14:8443/oms1350/data/npr/physicalConns?wdmConnectionType=WdmPortType_ots" # 读取第一个接口返回的物理连接数据,verify=False用于跳过自签名证书校验,正规可信任证书可删除该参数 # 如果接口需要鉴权,可先通过requests.get获取响应再转DataFrame,示例见注意事项 physical_conn_df = pd.read_json(first_url, verify=False) # 存储所有光纤特征数据,用于后续合并导出 all_fiber_data = [] # 遍历所有物理连接ID发送第二个请求 for conn_id in physical_conn_df["id"]: # 拼接第二个接口的请求地址,整数ID转字符串后拼接 second_url = f"https://10.200.35.14:8443/oms1350/data/npr/physicalConns/{conn_id}/fiberCharacteristic" try: # 发送第二个请求 resp = requests.get(second_url, verify=False, timeout=10) # 状态码非200时直接抛出异常 resp.raise_for_status() current_fiber_data = resp.json() # 方案1:每个ID单独导出为独立JSON文件,文件名携带ID区分 with open(f"fiber_characteristic_id_{conn_id}.json", "w", encoding="utf-8") as f: json.dump(current_fiber_data, f, ensure_ascii=False, indent=2) # 方案2:将数据加入合并列表,后续统一导出为全量JSON all_fiber_data.append({ "physical_conn_id": conn_id, "fiber_info": current_fiber_data }) except Exception as e: print(f"ID为{conn_id}的光纤特征请求失败,错误信息:{str(e)}") # 方案2配套代码:统一导出全量光纤特征数据为单个JSON with open("all_fiber_characteristics_total.json", "w", encoding="utf-8") as f: json.dump(all_fiber_data, f, ensure_ascii=False, indent=2)
注意事项
- 如果第一个接口需要鉴权(Token、账号密码等),替换第一个请求的代码为如下写法,请求头按实际要求补充即可:
headers = {"Authorization": "Bearer 你的实际鉴权Token"} first_resp = requests.get(first_url, headers=headers, verify=False, timeout=10) first_resp.raise_for_status() physical_conn_df = pd.DataFrame(first_resp.json()) - 若接口有请求频率限制,可在循环末尾添加
time.sleep(秒数)调整请求间隔,需提前导入time库 - 代码中两种导出方案可按需选择,不需要的方案可以直接删除对应代码段
内容的提问来源于stack exchange,提问作者Anselmo
相关产品推荐
相关产品推荐

