Search code examples
python-3.xpython-requestsmultipartform-data

Python Requests Post - Additional field is not recognized for file upload


I have to post a file using Multipart upload to a company-internal REST service. The endpoint needs the file as property "file" and it needs an additional property "DestinationPath". Here is what I do:

url = r"http://<Internal IP>/upload"

files = {
  "DestinationPath": "/some/where/foo.txt",
  "file": open("test.txt", "rb")
}

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

The server complains that it can't get the "DestinationPath". Full error message I receive is:

{'errors': {'DestinationPath': ['The DestinationPath field is required.']},
 'status': 400,
 'title': 'One or more validation errors occurred.',
 'traceId': '00-1993fbc53ab2ee418b683915dd7a440a-2338bd9cf34d414a-00',
 'type': 'https://tools.ietf.org/html/rfc7231#section-6.5.1'}

The file upload works in curl, thus it must be python specific.


Solution

  • Thanks to @etemple1 I found the solution to my question:

    url = r"http://<Internal IP>/upload"
    data = {
        "DestinationPath": "/some/where/foo.txt",
    }
    
    with open("test.txt", "rb") as content:
        files = {
            "file": content.read(),
        }
    
        response = requests.post(url, data=data, files=files)
    

    The data for the multipart upload needed to be divided between "data" and "files". They are later combined in the body of the http post by the requests library.