Sendpulse WhatsApp API报'tags should be an array'错误的排查与解决
问题原因及解决办法
错误原因
你代码里的核心问题是用params参数传递请求体数据。params的作用是把数据拼接到URL的查询参数里(比如?contact_id=xxx&tags=xxx),但Sendpulse的这个API要求数据以JSON格式放在请求体中。用params传递时,数组会被转成普通字符串,API无法识别出这是数组类型,所以返回"tags should be an array"的错误。
解决方法
把requests.post里的params=payload_data替换成json=payload_data。requests库会自动将字典序列化为JSON字符串,同时适配API要求的请求格式。
修改后的代码:
def add_tag(self, contact_id, tag_name): url = base_url_whatsapp + "/contacts/setTag" payload_data = { "contact_id": str(contact_id), "tags": [ tag_name ] } headers = { 'Authorization': f'Bearer {self.access_token}', 'Content-Type': 'application/json' } # 替换params为json,将数据放入请求体 response = requests.post(url, headers=headers, json=payload_data) if response.status_code == 200: print('Add Tag Successful') #print(response.json()) # If you expect a JSON response else: print('Request failed:', response.text)
内容的提问来源于stack exchange,提问作者economman
相关产品推荐
相关产品推荐

