Use the python Requests library to post Multipart-Encoded file

In this segment I’m going to show you how simple it is to post a Multipart-Encoded file to a RESTful api using the python Requests library using python 3.5.2.  So let’s get started. First you will need to install the python Requests library, to do that simply type this command into your terminal:

pip install requests

Once you have done that we can now get to the good stuff. Let’s take a look a this script then break it down line by line:

1
2
3
4
5
6
7
8
9
10
11
#!venv/bin/python
import requests
 
file = open('test.txt', 'rb')
url = 'https://example.com/api/files/'
headers = {'token': 'c203x302s30s03x0322x0320'}
payload = {'client_id': 1}
files = {'file': file}
r = requests.post(url, files=files, data=payload, headers=headers)
json_data = r.json()
print(json_data)

What’s going on here? Let’s start with the obvious:

1.) We are importing the requests library so we can make HTTP requests using get, post, put, delete etc…

2.) On line 4 we are opening a file(test.txt) in binary mode, which is recommended by the Requests docs because opening it in text mode may cause an error because Requests attempts to provide a Content-Length header for you, which is in bytes.

3.) On line 5 we are simply providing the url we plan on posting the file to.

4.) On line 6, for security reasons my api requires an authentication token for verification to be placed in the headers. You may or may not need this.

5.) On line 7, the payload is the data that I will be sending along with our file, and for me it’s a client id.

6.) And on line 8 we are assigning the file to a files dictionary. The Requests post method requires the files keyword argument to be an iterable list. If you attempt to post a the file itself without being in list context then you will get a ValueError.

7.) On line 9 we call requests.post() method and supply the arguments required to complete the request,  and store the response object in the “r” variable.

8.) And on line 10 we can call the json() method on the response object so our data will a JSON format.

9.) And lastly were merely are printing out the JSON response data.

And that’s really all there is to it. If you have any questions please feel free to comment below, thanks.

Further reading: Python Requests Library, JSON Intro

2 thoughts on “Use the python Requests library to post Multipart-Encoded file

  1. Sarang Sangram says:

    I tried the same block , but it throws an argument missing error in my case , even though everything is present :
    Code:

    sonheaderup={‘Content-Type’: ‘application/octet-stream’}

    file = open(‘install.pkg.gz’, ‘rb’)
    files = {‘file’: file}

    def upload_code():

    u = requests.post(“%s/api/sys/v2/updates” % (url), files=files, verify=False, headers=jsonheaderup)
    l = json.loads(u.text)

    upload_code()

    Error: {u’fault’: {u’message’: u’required input argument is missing (upload)’, u’code’: 400, u’name’: u’ERR_MISSING_ARG’}}

    Any idea about this error ?

    • red_shift says:

      It appears that you’re calling arguments that are out of scope, try adding the arguments to your function definition: eg: def upload_files(files, jsonheader). The function upload_code cannot see the variables files or jsonheaderup. You need to do 1 of 3 things. Add the arguments as mentioned above, add the global keywords to the files and jsonheaderup variables, or just remove the function definition. In a script like this, having a function definition is a bit much since you’re not reusing the code.

Leave a Reply to red_shift Cancel reply

Your email address will not be published. Required fields are marked *