How to Upload Files with Python’s Requests Library
Hello in this tutorial, we will see how to upload a file using the requests library in Python. We will cover the HTTP POST method to upload the files to a free httpbin service.
1. Introduction
To dig digger in this tutorial we will need to download and install requests
dependency from the PyPi website. Use the pip
command to install the requests
package.
Command
pip install requests
1.2 Setting up Python
If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.
2. How to Upload Files with Python’s Requests Library
Let us dive in with the programming stuff now. I am using JetBrains PyCharm as my preferred IDE. You’re free to choose the IDE of your choice.
2.1 Creating an implementation file
Add the following code to the python script. The script consists of a dictionary object to hold multiple names and files. Once the file list is ready we will send the HTTP POST request to a free bin service that can simulate the post-operation and return an HTTP response. The dummy files (named – file1.txt
and file2.txt
) used in this script can be download from the Downloads section.
file-upload.py
# Upload file using python requests library # import module import requests # url - http://httpbin.org/ # making use of a free httpbin service post_url = 'http://httpbin.org/post' # method to upload files def upload_files(files): response = requests.post(url=post_url, files=files) if response.ok: print('upload is successful.') # print(response.text) else: print('some error has occurred!') if __name__ == '__main__': # important to read the file in binary mode requests package determines the Content-Type header value in the # byte. if the file is not read in bytes mode incorrect value for the Content-Type header is determined resulting # in a file upload error. # 'rb' denotes 'read binary' files_to_be_uploaded = { "upload_file_1": open("upload/file1.txt", "rb"), "upload_file_2": open("upload/file2.txt", "rb"), } upload_files(files=files_to_be_uploaded) print('\ndone')
Run this python script and if everything goes well the output will be shown in the IDE console describing that the files were uploaded successfully.
Console output
upload is successful. done
That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!
3. Summary
In this tutorial, we learned:
- Introduction to
requests
library of Python to upload the files to a server - Sample programming stuff
You can download the source code of this tutorial from the Downloads section.
4. Download the Project
This was a tutorial on how to upload files with the python requests library.
You can download the full source code of this example here: How to Upload Files with Python’s Requests Library