How to send an array using requests.post (Python)? "Value Error: Too many values to unpack"
Solution 1:
You want to pass in JSON encoded data. See the API documentation:
Remember — All post bodies must be JSON encoded data (no form data).
The requests
library makes this trivially easy:
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)
By using the json
keyword argument the data is encoded to JSON for you, and the Content-Type
header is set to application/json
.
Solution 2:
Well, It turns out that all I needed to do was add these headers:
headers = {'Content-Type': 'application/json', 'Accept':'application/json'}
and then call requests
requests.post(url,data=json.dumps(payload), headers=headers)
and now i'm good!
Solution 3:
Always remember when sending an array(list) or dictionary in the HTTP POST request, do use json argument in the post function and set its value to your array(list)/dictionary.
In your case it will be like:
r = requests.post(url, headers=headers, json=data)
Note: POST requests implicitly convert parameter's content type for body to application/json.
For a quick intro read API-Integration-In-Python