Uploading Files with multipart/form-data Using requests_toolbelt in Python
This tutorial explains how to install the requests_toolbelt library and use its MultipartEncoder to upload single or multiple files via multipart/form-data in Python, including code examples and important header settings for API testing.
In API automation testing, Python developers often need to upload files using multipart/form-data. The requests_toolbelt library simplifies this process by providing the MultipartEncoder class.
Step 1: Install the library
pip install requests_toolbeltStep 2: Upload a single file
from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
url = "http://httpbin.org/post"
encoder = MultipartEncoder(
fields={
'file1': ('test.txt', open('../test.txt', 'rb')),
}
)
headers = {'Content-Type': encoder.content_type}
response = requests.post(url, data=encoder, headers=headers)
print(response.text)This example creates a MultipartEncoder with a single file field, sets the appropriate Content-Type header, and sends the POST request.
Step 3: Upload multiple files and additional data
from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
url = "http://httpbin.org/post"
encoder = MultipartEncoder(
fields=[
('file1', ('test.txt', open('../test.txt', 'rb'), 'text/plain')),
('file2', ('test.jpg', open('../test.jpg', 'rb'), 'image/jpeg')),
('field1', 'value1'),
('field2', 'value2')
]
)
headers = {'Content-Type': encoder.content_type}
response = requests.post(url, data=encoder, headers=headers)
print(response.text)Here, both files and regular form fields are included in the fields list, with explicit MIME types for the files.
Conclusion
The requests_toolbelt library’s MultipartEncoder makes constructing multipart/form-data payloads straightforward, enabling efficient file uploads during backend API testing.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.