You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

针对批量API请求,是否有比for循环更高效的实现方式?

如何高效批量发起70次API请求?

你猜的没错——并行发起请求确实是比串行循环高效得多的方案,毕竟串行模式下大部分时间都在等待API响应,并行可以把这些等待时间重叠起来,大幅缩短总耗时。针对70个请求的规模,以下是几种实用的实现思路:

1. 异步IO方案(推荐IO密集型场景)

对于API请求这种典型的IO密集型任务,异步IO是最轻量化的并行方式,不需要额外创建大量线程/进程,资源占用更低。以Python为例,用aiohttp+asyncio实现:

import aiohttp
import asyncio

async def fetch_single_item(session, item_id):
    url = f"https://api.example.com/items/{item_id}"
    async with session.get(url) as resp:
        if resp.status == 200:
            return await resp.json()
        else:
            return {"error": f"Request failed with status {resp.status}", "item_id": item_id}

async def batch_fetch(item_ids):
    # 用信号量控制并发数,避免一次性发70个请求触发API限流
    semaphore = asyncio.Semaphore(10)
    
    async def fetch_with_limit(item_id):
        async with semaphore:
            return await fetch_single_item(session, item_id)
    
    async with aiohttp.ClientSession() as session:
        tasks = [asyncio.create_task(fetch_with_limit(item_id)) for item_id in item_ids]
        # 等待所有任务完成,返回结果列表
        results = await asyncio.gather(*tasks)
        return results

# 假设你的条目列表是item_ids
item_ids = list(range(70))
final_results = asyncio.run(batch_fetch(item_ids))

2. 多线程方案

如果你的技术栈不支持异步,或者更习惯同步代码的写法,多线程也是不错的选择,同样能把等待API响应的时间利用起来。还是Python例子,用requests+ThreadPoolExecutor:

import requests
from concurrent.futures import ThreadPoolExecutor

def fetch_single_item(item_id):
    url = f"https://api.example.com/items/{item_id}"
    try:
        resp = requests.get(url)
        resp.raise_for_status()
        return resp.json()
    except requests.exceptions.RequestException as e:
        return {"error": str(e), "item_id": item_id}

def batch_fetch(item_ids):
    # 控制线程数,一般设为10-20即可,过多线程反而会增加开销
    with ThreadPoolExecutor(max_workers=10) as executor:
        # 批量提交任务并获取结果
        results = list(executor.map(fetch_single_item, item_ids))
        return results

item_ids = list(range(70))
final_results = batch_fetch(item_ids)

关键注意事项

  • API限流:先查清楚目标API的速率限制(比如每分钟允许多少请求),并发数不要超过限制,否则会收到429错误甚至被临时封禁。70个请求分10并发完全没问题,大部分API都能承受。
  • 异常处理:务必处理请求失败的情况(比如网络波动、API返回错误),避免一个请求失败导致整个批量任务中断。
  • 结果匹配:并行请求的返回顺序和你输入的条目顺序是对应的(上面的例子中results列表和item_ids顺序一致),不用担心结果错位。

内容的提问来源于stack exchange,提问作者JackW24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 21:01:22