pythonhttpcurlpython-requests

Having trouble converting a request to python requests


Hi I'm having issue in porting a curl request to python

curl --location 'https://XXXX.com/file/upload' --header 'access-token: XXXXXXXX' --header 'Cookie: JSESSIONID=D8545B9B0589ACD536E224A40537ED39' --form 'file=@"/C:/Users/xxxx/Documents/xxx.zip"' --form 'UploadData="{\"aaaa\":\"aaaa\",\"version\":\"26.005.10072\"}";type=application/json'

Here is my python code:

    url = "https://XXXXXX.com/symbol/upload"

    payload = {'UploadData': '{"aaaa":"aaaa","version":"23.005.10072"}'}

    
    files=[('file',('file',open(zipped_file_location,'rb')))]

    header = {
        'access-token': xxxxxxxxxxxxxx
    }
    
    response = requests.post(url, data=payload, headers=header,files=files)

I have tried postman code snippet feature but it didn't work. Getting 415 with the Python's code

**reason **is that 'Content-Type: application/json' is not getting added in my HTTP request under form-data; name="UploadData":

Content-Type: multipart/form-data; boundary=--------------------------488196413092784948314604
Cookie: JSESSIONID=5D96B5385CD957521F5E3DA2397ACE83
Content-Length: 6856215
 
----------------------------488196413092784948314604
Content-Disposition: form-data; name="file"; filename="xxxxx.zip"
<Symbols.zip>
----------------------------488196413092784948314604
Content-Disposition: form-data; name="UploadData"
Content-Type: application/json
{"xxxx":"yyyyy","version":"26.005.10072"}
----------------------------488196413092784948314604--

Solution

  • You should not use both data and files arguments with requests. Instead, you should populate the files parameter with both the file and the UploadData structures. Then you can set the Content-Type of the UploadData as you wish.

    See more information in this thread.