-1

I'm trying to pass a variable to the data field in requests.post() and I continue to get the error,

  Error Response: {'error': {'message': 'Exception while reading request', 
'detail': 'Cannod decode: java.io.StringReader@1659711'}, 'status': 'failure'}

Here is my code

#Fill array from CSV
temp=[]
for row in csv.iterrows():
    index, data = row
    temp.append(data.tolist())


#Create new asset for all assets in CSV
for index, row in enumerate(temp):
    make = temp[index][0]
    serial = str(temp[index][1])
    date = str(temp[index][2])
    response = requests.post(url, auth=(user, pwd), headers=headers, 
    data='{"asset_tag":"test1", "assigned_to":"test2", 
    "company":"test3", "serial_number":serial}')

I originally tried feeding it directly from the CSV using

str(temp[index][1])

This did not work, so I tried assigning str(temp[index][1]) to the variable serial and then passing the variable like that but that also results in the same error.

A point in the right direction would be great, thanks!

Kirk
  • 16,182
  • 20
  • 80
  • 112
t_wimms
  • 11
  • 1
  • 1
  • 4

3 Answers3

5

Instead of sending the request payload body in string, pass it in json form. requests.post accepts string in data variable and json in json variable. I faced a same issue while trying to make my first REST call to ServiceNow instance via Python. Hope this helps.

response = requests.post(url, auth=(user, pwd), headers=headers, 
    json={"asset_tag":"test1", "assigned_to":"test2", 
    "company":"test3", "serial_number":serial})
Milind Gokhale
  • 575
  • 2
  • 14
2

Remove the single quotes from the following :

data='{"asset_tag":"test1", "assigned_to":"test2", 
       "company":"test3", "serial_number":serial}' 

Use

data = {"asset_tag":"test1", "assigned_to":"test2", 
        "company":"test3", "serial_number":serial} 
JE_Muc
  • 5,403
  • 2
  • 26
  • 41
Sanjucta
  • 127
  • 1
  • 6
1

rather than passing data=data, take data as dict and pass it as json=data.

Prachit Patil
  • 413
  • 5
  • 9