在 Shopify ORDERS 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/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 个彼此不重复的。我想可能是第二个网址,只请求第二页,而不是进入第三页。因此我在做
first iteration = first page
second iteration = second page
third iteration = second page
所有这些都进入累积列表并停止循环,因为当累积超过计数时循环将停止。
当我在 shopify 中请求 ORDERS Endpoint 时,如何做到这一点。我正确地从下一页开始?
我尝试关注 shopify 的 tutorial in making paginated requests,但我不清楚。关于如何使用它。这个 page_info
变量让我很难理解在哪里可以找到它以及如何使用它。
答案 0 :(得分:0)
嗨!在 Shopify REST api 中,您每次 api 调用最多可以获得 250 个订单,如果有更多订单,您将从包含下一页请求 URL 的标头中获得 LINK
,例如
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 为上一个,1 为下一个。
运行此代码段以从标题中获取 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 但是如果您有两个以上的页面,请使用以下代码将下一个链接与上一个和下一个标志分开
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;
}