'Cannot Post CSV file in Python

I'm having problems with a CSV file upload with requests.post method in python 3.

from requests.auth import HTTPBasicAuth
import csv
import requests

user='myuser'
pw='mypass'
advertiserid='10550'
campaignid='12394'
url='http://example.example.com/api/edc/upload/'+advertiserid+'/'+campaignid+'/'+'?encoding=utf-8&fieldsep=%3B&decimalsep=.&date=DD%2FMM%2FYYYY&info=1&process=1'
csv="myfile.csv"

with open(csv, 'r') as f:
    r = requests.post(url, files={csv: f})
    print(r)

The output is 'Response [502]'

Any idea of what could be the problem?

Many thanks!



Solution 1:[1]

You can refer the documentation of Requests library here: post-a-multipart-encoded-file

Change your request line to:

r = requests.post(url, files={'report.csv': f})

Solution 2:[2]

Try opening it in binary mode? And with specific 'text/csv' mime type?

with open(csv, 'rb') as f:
    r = requests.post(url, files={'file': ('myfile.csv', f, 'text/csv', {'Expires': '0'})})
    print(r.text)

If it still does not work, try without the binary, but still with the rest. If it stiiill does not work, print the exact error message. And 502 (Bad Gateway) might just mean that you're not targetting the right url. (you're not targetting example.com, right?

Solution 3:[3]

csv="myfile.csv"

url='http://example.example.com/api/edc/upload/'+advertiserid+'/'+campaignid+'/'+'?encoding=utf-8&fieldsep=%3B&decimalsep=.&date=DD%2FMM%2FYYYY&info=1&process=1'

files = {'upload_file': open(csv,'rb')}

r = requests.post(url, files=files)

Solution 4:[4]

Imagine I have a rest API to import the CSV file (Multipart encoded file)

rest api call via postman

corresponding python request should be like below.

import requests

?
hierarchy_file_name = '/Users/herle/ws/LookoutLab/data/monitor/Import_Hierarchy_Testcase_v2.csv'

headers = {
  'x-api-key': **REST_API_KEY**,
  'x-api-token': **REST_API_TOKEN**,
  'accept': 'application/json'
}

files = {'file': (hierarchy_file_name, open(hierarchy_file_name, 'rb'), 'text/csv')}
url = "https://abcd.com"
response = requests.post(url +'/api/v2/core/workspaces/import/validate',
                        files=files, verify=False, headers=headers)
print("Created")
print(response)
print(response.text)

Note: Make sure that you don't add 'Content-Type': 'multipart/form-data' in the header

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sheshnath
Solution 2 Samuel GIFFARD
Solution 3 user5305519
Solution 4 Amrith Raj Herle