Home > Blockchain >  Python requests return empty response after file upload
Python requests return empty response after file upload

Time:06-24

I want to upload a file via Python requests. I have successful tries with Postman and Curl. On successful response, I get the file id, but using requests i get status code 200 and empty json.

Curl example:

curl --location --request POST 'http://someurl.com/api/file' \
--header 'Content-Type: multipart/form-data' \
--header 'Accept: application/json' \
--header 'Authorization: Basic TWFsZWtzZXkubHVraW55a2hfdGVzdDE6UWF6MVdzeEA=' \
--form 'file=@"1.png"' \
--form 'fileName="1.png"' \
--form 'fileType="image/png"'

Curl output:

{
    "fileId": 328446
}

Python requests:

import requests


session = requests.session()
files = {'file': ('1.png', open('1.png', 'rb'), 'image/png',)}
response = session.post('http://someurl.com/api/file', auth=HTTPBasicAuth('my_login', 'my_password'), files=files)
print(response.json())

requests output:

{}

I also tried to attach a file through this topic, but the version of the requests is older there

Python requests doesn't upload file

Postman form-data example

API POST request Example

CodePudding user response:

Found a solution. This code works

import requests
from requests.auth import HTTPBasicAuth


url = 'http://someurl.com/api/file'
payload={'fileName': '1.png', 'fileType': 'image/png'}
files= {'file': open('1.png','rb')}
response = requests.post(url, auth=HTTPBasicAuth('my_login', 'my_password'), data=payload, files=files)

print(response.json())
  • Related