Instagram Graph API批量请求返回Bad Request问题求助(获取用户收件箱对话消息)
Instagram Graph API批量请求返回Bad Request问题求助(获取用户收件箱对话消息)
我太懂你这种反复啃文档却搞不定批量请求,还一直收到Bad Request的憋屈感了!我之前对接Instagram Graph API时也踩过类似的坑,咱们一步步来排查和修正你的代码问题。
首先,先梳理下你代码里几个容易导致Bad Request的关键点,再给你调整后的完整代码:
常见问题排查&修正点
批量请求端点缺失版本号
你用的https://graph.facebook.com没有指定API版本,默认会使用旧版本,而旧版本可能不兼容你要调用的对话接口,必须加上和你获取对话列表一致的版本号(比如v17.0)。参数传递方式错误
你把批量请求的JSON字符串放在URL参数里,很容易因为字符串过长、特殊字符编码问题触发Bad Request,改成用POST表单传递参数更可靠。批量响应处理不严谨
默认返回的批量响应里,每个请求的body是JSON字符串,需要手动解析,而且要逐个检查单个请求是否出错,避免因为某一个请求失败导致整个流程卡壳。
调整后的完整代码
import json import requests import logging logger = logging.getLogger(__name__) @staticmethod def get_inbox_messages(ig_user_id: str, access_token: str): try: # 获取对话列表 url = ( f"https://graph.instagram.com/v17.0/me/conversations?platform=instagram" f"&access_token={access_token}" ) logger.info(f"Fetching inbox messages from: {url.replace(access_token, 'TOKEN_HIDDEN')}") response = requests.get(url) response.raise_for_status() conversations_data = response.json() if 'error' in conversations_data: raise ValueError(f"Instagram API error: {conversations_data['error'].get('message', 'Unknown error')}") # 提取对话ID conversation_ids = [conversation.get('id') for conversation in conversations_data.get('data', [])] if not conversation_ids: logger.info("收件箱中没有找到对话") return [] # 构造批量请求 batch_request = [] for conversation_id in conversation_ids: batch_request.append({ "method": "GET", "relative_url": f"{conversation_id}?fields=messages{{id,created_time}}" }) # 转换为JSON字符串(这里的双大括号是Python f-string转义单大括号的写法,没问题) batch_json = json.dumps(batch_request) # 调试时可以打印看看构造的批量请求是否正确 # print("构造的批量请求内容:", batch_json) # 批量请求的正确端点(带版本号) batch_url = "https://graph.facebook.com/v17.0" headers = {'Content-Type': 'application/x-www-form-urlencoded'} payload = { 'batch': batch_json, 'include_headers': 'false', 'access_token': access_token } # 发送批量请求(用表单传递参数) batch_response = requests.post(batch_url, data=payload, headers=headers) print("批量请求响应状态码:", batch_response.status_code) print("批量请求响应内容:", batch_response.text) batch_response.raise_for_status() # 处理批量响应 batch_data = batch_response.json() processed_data = [] for idx, resp in enumerate(batch_data): if 'error' in resp: logger.error(f"获取对话 {conversation_ids[idx]} 失败: {resp['error'].get('message')}") else: # 解析单个请求的响应体(因为include_headers为false,body是JSON字符串) try: conv_data = json.loads(resp['body']) processed_data.append(conv_data) except json.JSONDecodeError: logger.error(f"对话 {conversation_ids[idx]} 的响应不是有效JSON: {resp['body']}") return processed_data except Exception as e: logger.error(f"获取收件箱消息出错: {str(e)}") raise
额外调试建议
- 检查权限:确认你的access_token已经拿到
instagram_manage_messages和pages_show_list(关联Facebook Page时需要)的权限,未审核的测试应用要确保用户是测试人员。 - 验证对话ID:打印
conversation_ids确认提取的ID格式正确(比如是类似123456789的纯数字ID)。 - 查看批量请求内容:打开代码里的调试打印,确认生成的
batch_json格式是否符合官方要求,有没有语法错误。
内容来源于stack exchange
相关产品推荐
相关产品推荐

