2

I have Java spring server that requires the Content-Type of the requests being sent to the server to be multipart/form-data.

I can correctly send requests to the server with postman:

enter image description here

enter image description here

However, I got The current request is not a multipart request error when trying to send the request with requests module in python3.

My python code is:

import requests

headers = {
  'Authorization': 'Bearer auth_token'
}

data = {
  'myKey': 'myValue'
}

response = requests.post('http://127.0.0.1:8080/apiUrl', data=data, headers=headers)
print(response.text)

If I add 'Content-Type': 'multipart/form-data' to the header of the request, the error message then becomes Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found.

How can I make the same request as postman sends with python?

Brian
  • 12,145
  • 20
  • 90
  • 153
  • Possible duplicate: https://stackoverflow.com/a/22974646/6890912 – blhsing Jun 26 '18 at 03:38
  • @blhsing I'm not sending a file. I send texts. – Brian Jun 26 '18 at 03:45
  • Then what's the point of using `'Content-Type': 'multipart/form-data'` if you're not actually sending files? – dmitryro Jun 26 '18 at 03:49
  • @dmitryro I also want to the answer of your question. But the server was designed by someone else in my company many years ago. And that person has left the company. – Brian Jun 26 '18 at 03:52
  • Then probably the way the request is sent has to change so it will be a regular payload with POST, not multipart - something to change in POSTMAN at the first place. – dmitryro Jun 26 '18 at 03:53

1 Answers1

10

requests's author thinks this situation is not pythonic, so requests doesn't support this usage natively.

You need to use requests_toolbelt which is an extension maintained by members of the requests core development team, doc, example:

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

m = MultipartEncoder(
    fields={'field0': 'value', 'field1': 'value',
            'field2': ('filename', open('file.py', 'rb'), 'text/plain')}
    )

r = requests.post('http://httpbin.org/post', data=m,
                  headers={'Content-Type': m.content_type})
Sraw
  • 18,892
  • 11
  • 54
  • 87