oznu oznu - 10 days ago 5
JSON Question

Python Requests: Post JSON and file in single request

I need to do a API call to upload a file along with a JSON string with details about the file.

I am trying to use the python requests lib to do this:

import requests

info = {
'var1' : 'this',
'var2' : 'that',
}

data = json.dumps({
'token' : auth_token,
'info' : info,
})

headers = {'Content-type': 'multipart/form-data'}

files = {'document': open('file_name.pdf', 'rb')}

r = requests.post(url, files=files, data=data, headers=headers)


This throws the following error:

raise ValueError("Data must not be a string.")
ValueError: Data must not be a string


If I remove the 'files' from the request, it works.

If I remove the 'data' from the request, it works.

If I do not encode data as JSON it works.

For this reason I think the error is to do with sending JSON data and files in the same request.

Any ideas on how to get this working?

Answer

Don't encode using json.

import requests

info = {
    'var1' : 'this',
    'var2'  : 'that',
}

data = {
    'token' : auth_token,
    'info'  : info,
}

headers = {'Content-type': 'multipart/form-data'}

files = {'document': open('file_name.pdf', 'rb')}

r = requests.post(url, files=files, data=data, headers=headers)

Note that this may not necessarily be what you want, as it will become another form-data section.