使用Shopify Orders API获取全量订单遇分页遗漏及参数限制问题求助
Shopify API 获取全量订单问题排查与修复
一、订单丢失核心原因:默认状态过滤
Shopify Orders API 默认仅返回状态为open和closed的订单,已取消、已归档等状态的订单会被自动过滤。要获取所有状态的订单,必须在请求参数中添加:
'status': 'any'
二、分页逻辑优化
你的分页实现存在三个关键问题:
- 固定循环100次,若订单总数超过25000条(100×250)会提前终止;
- 提取
page_info时未区分rel="next"和rel="prev"的链接,可能拿到错误的分页标记; - 当最后一页刚好返回250条时,会跳过该页数据(原代码仅在订单数<250时才添加)。
正确的分页处理逻辑
- 循环终止条件改为无法从响应头中获取
rel="next"的链接; - 提取
page_info时精准匹配rel="next"的目标链接; - 每次请求后直接添加当前页订单,无需判断订单数量是否小于250。
三、修复后的完整代码
import requests import re import pandas as pd orders = [] # 初始参数添加status=any以获取所有状态订单,保留时间范围和分页上限 params = { 'created_at_min': '2023-05-11T00:00:00%2B05:30', 'created_at_max': '2023-05-11T23:59:59%2B05:30', 'limit': '250', 'status': 'any' # 关键参数:获取全状态订单 } response = requests.get(url, headers=headers, params=params) # 处理第一页数据 if 'orders' in response.json(): orders.extend([item['name'] for item in response.json()['orders']]) print(f"当前累计订单数:{len(orders)}") while True: try: # 检查响应头是否存在Link字段 if 'Link' not in response.headers: break link_header = response.headers['Link'] # 匹配rel="next"链接中的page_info next_page_match = re.search(r'<[^>]*page_info=([^&>]+)[^>]*>; rel="next"', link_header) if not next_page_match: break page_info = next_page_match.group(1) print(f"下一页page_info:{page_info}") # 构造下一页请求参数,无需rel参数,仅保留page_info、limit和status params = {'page_info': page_info, 'limit': '250', 'status': 'any'} response = requests.get(url, headers=headers, params=params) # 添加当前页订单 current_orders = response.json().get('orders', []) orders.extend([item['name'] for item in current_orders]) print(f"当前累计订单数:{len(orders)}") # 若当前页订单数小于250,确认是最后一页 if len(current_orders) < 250: break except Exception as e: print(f"分页出错:{str(e)}") break # 转换为DataFrame orders_df = pd.DataFrame(orders, columns=["Order ID"]) print(f"最终获取订单总数:{len(orders_df)}")
关键注意事项
status=any必须全程携带:初始请求和所有分页请求都要包含,否则后续分页仍会过滤非活跃状态订单;- Shopify API分页仅需
page_info参数,原代码中的rel='next'是多余的; - 增加响应字段判断(如
response.json().get('orders', [])),避免因API返回异常导致程序崩溃。
内容的提问来源于stack exchange,提问作者Droning Hangman
相关产品推荐
相关产品推荐

