首页 > 解决方案 > 如何在 PowerQuery/PowerBI 的 API 请求中迭代/循环访问下一页?

问题描述

正在使用的 API 被调用并返回如下数据(从邮递员那里尝试过):

示例调用 1:

https://api.aaaaaa.com/api/v1/survey?step=1&limit=1000
{
    "_links": {
        "base": "http://api.aaaaaa.com",
        "self": "/api/v1/survey?step=1&limit=1000",
        "next": "/api/v1/survey?step=2&limit=1000"
    },
    "start": 1,
    "limit": 1000,
    "size": 1000,
    "total": 3158,
    "results": [
        {....//data
         }
]

示例调用 2:

https://api.aaaaaa.com/api/v1/survey?step=2&limit=1000
{
    "_links": {
        "base": "http://api.aaaaaa.com",
        "self": "/api/v1/survey?step=2&limit=1000",
        "prev": "/api/v1/survey?step=1&limit=1000",
        "next": "/api/v1/survey?step=3&limit=1000"
    },
    "start": 1001,
    "limit": 1000,
    "size": 1000,
    "total": 3158,
    "results": [
        {....//data
         }
     ]

在 Power BI/Power Query 中,我试图迭代以获取下一个链接并附加/结合基本 API url 以获取下一页/记录集。

但是,我只在列表中获得 1 页,即 GeneratedList {0}。然而,从 Postman 的响应中可以看出它有 3 页(step=1,2,3)。因此,期望在每个页面的列表中返回 3 个值。这是代码:

let 
   BaseUrl = "https://api.aaaaaa.com",
   SurveyUrl = Text.Combine(BaseUrl,"/api/v1/survey?step=1&limit=1000"),
   Options = [ApiKeyName= "TOKEN"],
   url = Web.Contents(SurveyUrl, [Headers=[TOKEN="zzzzzzzzzzzzzzz"]]),

 FnGetOnePage =
  (url) as record =>
   let
   Source = Json.Document(url),
   data = try Source[results] otherwise null,
   next = try Source[_links][next] otherwise null,
   res = [Data=data, Next=Text.Combine(SurveyUrl, next)]
   in
    res,
 
 GeneratedList =
  List.Generate(
   ()=>[i=0, res = try FnGetOnePage(url) otherwise null],
   each [res][Data]<>null,
   each [i=[i]+1, res = try FnGetOnePage([res][Next]) otherwise null],
   each [res][Data])
   in
    GeneratedList

请建议/帮助在上述步骤中哪里出错了?

我能想到的另一种方法是直接循环/迭代url 中的步数值,即 ...

/api/v1/survey?step=< loop_over_this_number >&limit=1000

; 但没试过。因此,欢迎提出任何建议。

参考:- https://datachant.com/2016/06/27/cursor-based-pagination-power-query/

谢谢! 在此处输入图像描述

标签: paginationpowerbipowerquerym

解决方案


推荐阅读