Power Query分页查询求助:适配带Base64页码的API自动分页
Power Query 自动分页解决方案(适配带Base64编码页码的Next链接)
完整M代码实现
let // 定义递归分页函数 GetPage = (relativePath as text) as list => let // 发起API请求 Source = Json.Document( Web.Contents( "https://apis-us.MyWeb.com", [ RelativePath = relativePath, Headers = [ Authorization = "Bearer MyToken", #"Content-Type" = "application/vnd.api+json" ] ] ) ), // 提取当前页数据 CurrentPageData = Source[data], // 检查是否存在下一页链接,无则返回null NextLink = try Source[links][next] otherwise null, // 递归获取下一页数据(存在Next链接时继续调用) NextPageData = if NextLink <> null then GetPage(NextLink) else {}, // 合并当前页与后续页数据 CombinedData = CurrentPageData & NextPageData in CombinedData, // 初始调用:第一页的相对路径(MQ==是数字1的Base64编码) InitialRelativePath = "/v1/dept/deptID/sometable?page[size]=100&page[number]=MQ==", // 执行递归获取全量数据 FullData = GetPage(InitialRelativePath), // 转换为表格格式(可根据实际数据结构调整) ConvertToTable = Table.FromList(FullData, Splitter.SplitByNothing(), null, null, ExtraValues.Error) in ConvertToTable
关键逻辑说明
- 递归自动分页:
GetPage函数接收相对路径参数,每次请求后自动读取返回结果中的links[next]字段,存在则递归调用自身,直到无下一页时停止。 - 相对路径复用:将基础域名单独传入
Web.Contents,API返回的next链接直接作为相对路径使用,无需手动解析Base64页码或拼接参数。 - 数据合并:通过列表拼接(
&)将所有页的数据合并为完整列表,最后按需转换为表格格式。
注意事项
- 替换代码中的
MyToken为实际授权令牌,确保API权限有效。 - 初始请求的相对路径可简化为
/v1/dept/deptID/sometable?page[size]=100(若API默认返回第一页),无需手动指定Base64页码。 - 若API有请求频率限制,可在函数中添加延迟步骤(如
Wait = Function.InvokeAfter(() => null, #duration(0,0,0,1))),避免触发限流。
内容的提问来源于stack exchange,提问作者Richard
相关产品推荐
相关产品推荐

