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

在Cloud Workflows中如何通过nextPageToken实现API结果分页遍历?

Cloud Workflows 基于nextPageToken的分页迭代实现方案

问题根因

你之前的方案无法正常运行的核心原因是:Cloud Workflows 的语法规则中,直接访问字典中不存在的字段会直接抛出执行异常,而非返回 falsy 值。当API返回结果中没有nextPageToken字段时,result.nextPageToken的写法会直接中断流程,不会进入你预期的条件分支。

正确实现步骤

完整的可运行workflow示例如下:

main:
  steps:
    # 初始化分页参数、结果存储变量,可根据需求增加最大循环次数限制变量
    - init:
        assign:
          - currentPageToken: ""
          - totalResult: []
          # 可选:增加最大分页限制避免死循环
          - maxPage: 100
          - currentPageCount: 0

    # 调用目标API,动态传入分页token
    - call_target_api:
        call: http.get
        args:
          url: 替换为你的API请求地址
          auth:
            type: OAuth2
          query:
            pageToken: ${currentPageToken}
            # 补充其他API需要的查询参数
        result: apiResponse

    # 合并当前页结果到总结果集合
    - merge_page_data:
        assign:
          - totalResult: ${list.concat(totalResult, apiResponse.body.data)}
          - currentPageCount: ${currentPageCount + 1}

    # 安全判断是否存在下一页,使用内置containsKey方法避免访问不存在字段的异常
    - check_has_next_page:
        switch:
          - condition: ${containsKey(apiResponse.body, "nextPageToken") AND apiResponse.body.nextPageToken != "" AND currentPageCount < maxPage}
            assign:
              - currentPageToken: ${apiResponse.body.nextPageToken}
            next: call_target_api
        # 没有下一页时跳转到结果返回步骤
        next: return_all_result

    # 返回最终聚合的全量结果
    - return_all_result:
        return: ${totalResult}

注意事项

  • 你可以根据调用的API实际返回规则调整判断条件,部分API无后续页时会返回空字符串的nextPageToken,部分API会直接不返回该字段,示例中同时兼容了两种场景
  • 示例中添加了最大分页限制,避免API异常返回无效nextPageToken导致的死循环,可根据实际需求调整数值或删除该限制
  • 若你使用的API分页参数名、返回数据字段名和示例不同,对应替换字段名即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:06:09