我正在尝试使用requests.post向WheniWork API发送一个请求数组(列表),并且我一直收到两个错误中的一个。当我以列表的形式发送列表时,我会收到一个解包错误,当我以字符串的形式发送列表时,我会收到一个错误,要求我提交一个数组。我认为这与请求如何处理列表有关。下面是一些例子:
url='https://api.wheniwork.com/2/batch'
headers={"W-Token": "Ilovemyboss"}
data=[{'url': '/rest/shifts', 'params': {'user_id': 0,'other_stuff':'value'}, 'method':'post',{'url': '/rest/shifts', 'params': {'user_id': 1,'other_stuff':'value'}, 'method':'post'}]
r = requests.post(url, headers=headers,data=data)
print r.text
# ValueError: too many values to unpack
只需将数据的值用引号括起来:
url='https://api.wheniwork.com/2/batch'
headers={"W-Token": "Ilovemyboss"}
data="[]" #removed the data here to emphasize that the only change is the quotes
r = requests.post(url, headers=headers,data=data)
print r.text
#{"error":"Please include an array of requests to make.","code":5000}
您需要传入JSON编码的数据。请参见API documentation:
requests
库使这变得非常简单:通过使用
json
关键字参数,数据被编码为JSON,并且Content-Type
头被设置为application/json
。好吧,结果我只需要添加这些标题:
然后呼叫请求
现在我好了!
在发送HTTP POST请求中的数组(list)或字典时,请务必记住在POST函数中使用json参数并将其值设置为数组(list)/dictionary。
在你的情况下会是:
注意:POST请求隐式地将body的参数内容类型转换为application/json。
快速介绍阅读API-Integration-In-Python
相关问题 更多 >
编程相关推荐