Backend Development 3 min read

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.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Uploading Files with multipart/form-data Using requests_toolbelt in Python

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_toolbelt

Step 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.

PythonFile UploadAPI TestingRequestsmultipartrequests_toolbelt
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.