1

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

1 Answer 1

0

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())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.