如何实现API页码循环遍历,拉取从第一页到最后一页的全量数据
分页拉取API完整数据的循环逻辑实现
我们优先用do-while循环实现该需求,该结构天然适配「至少请求一次接口」的分页场景,逻辑如下:
核心逻辑说明
- 终止条件:你设置的单页请求上限是1000条,当某一页返回的商品列表长度小于1000时,说明已经到最后一页,终止循环
- 性能优化:所有页数据全部拉取完成后再统一写入表格,避免频繁调用表格接口导致运行卡顿
- 表头复用:仅在第一次请求时提取表头,避免重复写入
修改后的完整代码
function dearAPI(endpoint,sheetname,dig) { // 配置项 const LIMIT = 1000; const allDataRows = []; let pagenumber = 1; let headers = null; let currentPageProducts = []; do { // 发请求拉取当前页数据 const response = UrlFetchApp.fetch( `https://inventory.dearsystems.com/externalapi/v2/${endpoint}?page=${pagenumber}&limit=${LIMIT}`, { 'method':'get', headers: { "api-auth-accountid": accountID, "api-auth-applicationkey": secret, }, "contentType": 'application/json' } ); const json = JSON.parse(response.getContentText()); currentPageProducts = json.Products || []; // 第一次请求时提取表头 if (pagenumber === 1 && currentPageProducts.length > 0) { headers = [Object.keys(currentPageProducts[0])]; } // 把当前页数据转成行格式存入总数组 for(let i = 0; i < currentPageProducts.length; i++){ allDataRows.push(Object.values(currentPageProducts[i])); } // 页码+1准备拉取下一页 pagenumber++; // 如果API有返回总页码,也可以把终止条件改成 pagenumber <= 总页码 } while (currentPageProducts.length === LIMIT) // 所有数据拉取完成后统一写入表格 const sheet = SpreadsheetApp.getActiveSheet(); // 写入表头 sheet.getRange(1,1,headers.length,headers[0].length).setValues(headers); // 写入所有数据,从第二行开始 if (allDataRows.length > 0) { sheet.getRange(2,1,allDataRows.length,allDataRows[0].length).setValues(allDataRows); } }
可选优化点
- 如果请求频率过高触发API限流,可以在循环末尾加
Utilities.sleep(1000)调整请求间隔 - 可以加错误捕获逻辑,避免某一页请求失败导致整个脚本终止
内容的提问来源于stack exchange,提问作者Victoria
相关产品推荐
相关产品推荐

