Home > other >  How to send CSV to Postman via Python post requests?
How to send CSV to Postman via Python post requests?

Time:06-22

I am trying to send a Post request to Postman via Python with the requests library. The file works when I do it manually via Postman's GUI. This is what I have:

csv_ = df.to_csv()
url = 'url.com'
headers = {'Authorization': 'my password'}
data = {'file': csv_, 'template_id':3, 'entity':'product', 'simulation':0}
r = requests.post(url, headers=headers, files=data)

I have also tried this:

url = 'url.com'
headers = {'Authorization': 'my password'}
data = {'file': open('file.csv', 'rb'), 'template_id':3, 'entity':'product', 'simulation':0}
r = requests.post(url, headers=headers, files=data)

But both ways I get this error: 422 {"success":false,"error":{"code":"invalid_export_request","message":["The entity must be a string."]}} . I have tried both converting the ints in data to strings and excluding them, but I still get the error. Why is this happening?

CodePudding user response:

I was able to send file this way:

data = {'file': (file_name, open(file_path, 'rb').read(), 'form-data') }

but maybe, deepens on particular implementation on the server side.

CodePudding user response:

One of my coworkers ended up helping me with this. in Postman when you click the </> icon it shows you what the code should look like. Anyway, this is what I have now that works:

url = 'url.com'
payload={'template_id': '3',
    'entity': 'product',
    'simulation': '0'}
    files=[
      ('file',('Main Product Template.csv',open(filename,'rb'),'text/csv'))
    ]
    headers = {
      'scope': 'english',
      'Authorization': 'my password',
      'Cookie': 'keysmash'
        }
    r = requests.request("POST", url, headers=headers, data=payload, files=files)
    return (r, r.text)
  • Related