基于官方示例发起ChannelAdvisor API批量请求的技术问询
使用Python的requests库调用ChannelAdvisor批量API请求
我整理了一套完整的代码示例,帮你用requests库实现ChannelAdvisor的批量更新库存请求,完全对应你参考的批量请求场景:
import requests import uuid # 替换成你的实际access token ACCESS_TOKEN = "xxxxxx" BATCH_URL = f"https://api.channeladvisor.com/v1/$batch?access_token={ACCESS_TOKEN}" # 生成唯一的boundary字符串,用于分隔多部分请求 boundary = str(uuid.uuid4()).replace("-", "") # 构造批量请求中的各个子请求(这里以3个商品库存更新为例) sub_requests = [ { "method": "POST", "path": "/v1/InventoryItems(12345)/UpdateQuantity", # 替换成你的目标商品ID "body": { "UpdateType": "Unshipped", "Quantity": 10 } }, { "method": "POST", "path": "/v1/InventoryItems(67890)/UpdateQuantity", # 替换成你的目标商品ID "body": { "UpdateType": "Unshipped", "Quantity": 5 } }, { "method": "POST", "path": "/v1/InventoryItems(11223)/UpdateQuantity", # 替换成你的目标商品ID "body": { "UpdateType": "Unshipped", "Quantity": 15 } } ] # 组装multipart/mixed格式的请求体 request_body = [] for req in sub_requests: # 子请求的起始分隔符 request_body.append(f"--{boundary}") # 子请求的头部标识 request_body.append('Content-Type: application/http') request_body.append('Content-Transfer-Encoding: binary') request_body.append('') # 子请求的HTTP行(方法+路径+版本) request_body.append(f"{req['method']} {req['path']} HTTP/1.1") request_body.append('Content-Type: application/json') request_body.append('') # 子请求的JSON内容 request_body.append(requests.utils.dumps(req['body'])) request_body.append('') # 添加请求体的结束分隔符 request_body.append(f"--{boundary}--") # 把列表拼接成完整的请求字符串,用换行分隔 final_body = '\n'.join(request_body) # 设置请求头部 headers = { "Content-Type": f"multipart/mixed; boundary={boundary}", "Content-Length": str(len(final_body)) } # 发起POST请求 response = requests.post(BATCH_URL, headers=headers, data=final_body) # 打印响应结果用于调试 print(f"响应状态码: {response.status_code}") print(f"响应内容: {response.text}")
关键细节说明:
- Boundary生成:用UUID生成唯一字符串,避免和请求内容冲突,保证多部分请求的正确分隔
- 子请求格式:每个子请求严格遵循HTTP协议格式,头部和体之间必须保留空行,否则会被API判定为格式错误
- 参数替换:务必把代码中的
ACCESS_TOKEN替换成你的有效令牌,同时更新子请求里的商品ID和库存数值 - 错误排查:如果返回格式错误,可以检查boundary在请求头和请求体中是否完全一致,或者JSON体是否存在语法问题
内容的提问来源于stack exchange,提问作者Rudolf Banki
相关产品推荐
相关产品推荐

