Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an array using requests.post (Python)? "Value Error: Too many values to unpack"

I'm trying to send an array(list) of requests to the WheniWork API using requests.post, and I keep getting one of two errors. When I send the list as a list, I get an unpacking error, and when I send it as a string, I get an error asking me to submit an array. I think it has something to do with how requests handles lists. Here are the examples:

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 

Simply wrapping the value for data in quotes:

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} 
like image 770
Bobby Battista Avatar asked Jul 01 '15 18:07

Bobby Battista


People also ask

How do you call a post in Python?

To create a POST request in Python, use the requests. post() method. The requests post() method accepts URL. data, json, and args as arguments and sends a POST request to a specified URL.

What is payload in Python request?

JSON Payload Example [Python Code] A request payload is data that clients send to the server in the body of an HTTP POST, PUT, or PATCH message that contains important information about the request.


2 Answers

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!

like image 40
elad silver Avatar answered Oct 05 '22 21:10

elad silver


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.

like image 53
Martijn Pieters Avatar answered Oct 05 '22 20:10

Martijn Pieters