HubSpot API分页获取数据Power BI M代码报错求助
问题分析与修复方案
问题概述
一段调用HubSpot API的Power BI M代码曾正常运行,现在在outputList语句处报错。已知initReq[paging][next][after]存在有效数据,但函数因引用不含分页数据的results字段失败。
核心问题排查
- 未做空值校验的嵌套引用:代码直接使用
initReq[results]、newReq[paging][next][after]这类嵌套字段,一旦API返回的JSON结构变化(比如某页无results、paging层级缺失),就会触发引用错误。 - 重复API请求:
gather函数里多次调用Web.Contents(uri, headers),既浪费API配额,也可能因网络波动导致前后返回不一致。 - 分页逻辑错误:首次调用
gather时传入原始apiUrl,而非带分页标记的URL,会导致重复请求第一页数据,陷入无效循环。
修复后的代码
let apiBase = "https://api.hubapi.com/crm/v3/objects/deals?limit=100&archived=false", accessToken = "xxxxxxxxxxxx", headers = [Headers = [ #"Content-Type" = "application/json", Authorization = "Bearer " & accessToken ]], // 封装API请求函数,统一处理请求与解析 getApiPage = (uri as text) => let response = try Web.Contents(uri, headers) otherwise error "API请求失败", json = try Json.Document(response) otherwise error "JSON解析失败", // 安全获取results,不存在则返回空列表 results = try json[results] otherwise {}, // 安全获取下一页标记,不存在则返回null nextAfter = try json[paging][next][after] otherwise null in [Results = results, NextAfter = nextAfter], // 初始化第一页数据 firstPage = getApiPage(apiBase), initData = firstPage[Results], // 递归分页获取函数 gatherPages = (accumulatedData as list, nextAfterToken as text) => let nextUri = apiBase & "&after=" & nextAfterToken, currentPage = getApiPage(nextUri), updatedData = List.Combine({accumulatedData, currentPage[Results]}), nextToken = currentPage[NextAfter] in if nextToken = null then updatedData else @gatherPages(updatedData, nextToken), // 主逻辑:判断是否需要分页 outputList = if firstPage[NextAfter] = null then initData else gatherPages(initData, firstPage[NextAfter]) in outputList
关键修复点
- 统一请求封装:用
getApiPage函数处理所有API请求,对results和分页标记做空值校验,避免直接引用嵌套字段报错。 - 减少重复请求:每个分页URL仅请求一次,避免多次调用
Web.Contents引发的配额浪费或数据不一致问题。 - 修正分页逻辑:首次递归传入第一页返回的分页标记,确保从第二页开始获取数据。
- 增强错误处理:在请求、解析环节添加
try otherwise,错误信息更明确,避免脚本直接崩溃。
内容的提问来源于stack exchange,提问作者Terran Brown
相关产品推荐
相关产品推荐

