Bob*_*sta 46 python api python-requests
我正在尝试使用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
Run Code Online (Sandbox Code Playgroud)
只需将数据的值包装在引号中:
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}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 69
您想传入JSON编码数据.请参阅API文档:
请记住 - 所有帖子主体必须是JSON编码数据(无表格数据).
该requests库使得这个很轻松:
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',
},
]
requests.post(url, json=data, headers=headers)
Run Code Online (Sandbox Code Playgroud)
通过使用json关键字参数,数据将被编码为JSON,并且Content-Type标头设置为application/json.
ela*_*ver 17
好吧,事实证明我需要做的就是添加这些标题:
headers = {'Content-Type': 'application/json', 'Accept':'application/json'}
Run Code Online (Sandbox Code Playgroud)
然后调用请求
requests.post(url,data=json.dumps(payload), headers=headers)
Run Code Online (Sandbox Code Playgroud)
现在我很好!
切记在HTTP POST请求中发送数组(列表)或字典时,请在post函数中使用json参数并将其值设置为array(list)/ dictionary。
在您的情况下,它将像:
r = request.post(URL,headers = headers,json = data)
注意: POST请求会将主体的参数内容类型隐式转换为application / json。
快速入门介绍,请参阅Python中的API集成
| 归档时间: |
|
| 查看次数: |
41501 次 |
| 最近记录: |