Shopify API 通过订单分页以获得准确的计数

Shopify API Paginate Through Orders to Get Accurate Count

在 Shopify 订单 API 中,我使用

/admin/api/2021-01/orders/count.json

为了获取订单数,所以想获取所有的订单。通过遵循 REST API 文档,我使用了两个端点来执行此操作。

/admin/api/2021-01/orders.json?status=any

/admin/api/2021-01/orders.json?limit=250&status=any; rel=next

首先,我将使用第一个端点请求订单,在列表中我最多可以得到 50 orders/items。

然后使用计数器作为限制,假设我从 orders/count.json

的响应中获得了 550 个订单

我愿意:

accumulated = []
iter = 0
while True:
    if len(accumulated) > count:
        break
    if iter != 1:
        url = #user first url
    else:
        url = $use second url that has next

    items = #make a request here for that url and save each order item
    accumulated+=items #this saves each list to the accumulated list so we know that we hit the count

但出于某种原因,我只得到了一小部分计数。可以说在 550 个计数中,我只得到 350 个不是彼此重复的。我在想,也许第二个 url,只请求第二页而不继续到第三页。因此我在做

first iteration = first page
second iteration = second page
third iteration = second page

所有这些都进入累积列表并停止循环,因为当累积超过计数时循环将停止。

在 shopify 中请求 ORDERS Endpoint 时如何做到这一点。我从下一页开始正确吗?

我尝试关注 shopify 的 tutorial in making paginated requests,但我不清楚。关于如何使用它。这个 page_info 变量让我很难理解在哪里可以找到它以及如何使用它。

喂!在 Shopify REST api 中,每次 api 调用最多可以获得 250 个订单,如果有更多订单,您会从 header 获得 LINK,其中包含下一个 URL页面请求如 Here you can see I have LINK variable in my response headers you just need to get this LINK and check for rel='next' flag

但是请记住,当您点击新的 URL 并且您仍然有更多的订单要提取时,Header 发送 LINK 两个 URL 1 for Previous下一个为 1。

运行 这个片段从 headers

得到 LINK
var flag = false;
var next_url = order.headers.link;
if(next_url){
  flag = true
  next_url = next_url.replace("<","");
  next_url = next_url.replace(">", "");
  var next_url_array = next_url.split('; ');
  var link_counter_start = next_url_array[0].indexOf("page_info=")+10;
  var link_counter_length = (next_url_array[0].length);
  var next_cursor="";
  var link_counter;
  for(link_counter=link_counter_start; link_counter<link_counter_length; link_counter++){
    next_cursor+=(next_url_array[0][link_counter])
  }
}

对于第一个 api 但如果您有超过两页,请使用以下代码将下一个 link 与上一个 link 和下一个标志

分开
next_url = order.headers.link;
      var next_url_array,
       link_counter_start, link_counter_length,
        link_counter;
      if(next_url.includes(',')){
        next_url = next_url.split(',');
        next_url = next_url[1];
      }
  
  next_url = next_url.replace("<","");
  next_url = next_url.replace(">", "");
  next_url_array = next_url.split('; ');
  link_counter_start = next_url_array[0].indexOf("page_info=")+10;
  link_counter_length = (next_url_array[0].length);
  next_cursor="";
  for(link_counter=link_counter_start; link_counter<link_counter_length; link_counter++){
    next_cursor+=(next_url_array[0][link_counter])
  }
  if(next_url_array[1] != 'rel="next"'){
    flag = false;
  }