python requests multipart/form-data

Python Requests Multipart/Form-Data

If you're using Python to send data over the internet, there's a good chance you'll need to send multipart/form-data at some point. This is a way of sending files and other binary data over HTTP. Python's requests module makes it easy to send this type of data, and there are a few different ways you can do it.

Using the Files Parameter

The easiest way to send multipart/form-data with requests is to use the files parameter. This allows you to specify a dictionary of files to send along with your request. Here's an example:


import requests

url = 'https://example.com/upload'
files = {'file': open('myfile.txt', 'rb')}

response = requests.post(url, files=files)
  

In this example, we're sending a file called myfile.txt to the URL https://example.com/upload. The open() function is used to open the file in binary mode ('rb') so that it can be sent over the internet. The files parameter is a dictionary where the keys are the names of the files and the values are the file objects.

Using the Data and Files Parameters

If you need to send both files and regular form data in the same request, you can use the data parameter as well. Here's an example:


import requests

url = 'https://example.com/upload'
data = {'name': 'John'}
files = {'file': open('myfile.txt', 'rb')}

response = requests.post(url, data=data, files=files)
  

In this example, we're sending a file called myfile.txt as well as a regular form field called 'name'. The data parameter is a dictionary where the keys are the field names and the values are the field values.

Using the Request Module to Build Your Own Multipart Request

If you need more control over the multipart/form-data request, you can use the Request module from the requests library to build your own request. Here's an example:


import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

url = 'https://example.com/upload'
file_data = open('myfile.txt', 'rb').read()

multipart_data = MultipartEncoder(
    fields={
        'name': 'John',
        'file': ('myfile.txt', file_data, 'text/plain')
    }
)

headers = {
    'Content-Type': multipart_data.content_type
}

response = requests.post(
    url,
    data=multipart_data,
    headers=headers
)
  

In this example, we're using the requests_toolbelt library to create a MultipartEncoder object. This allows us to specify the content type for each file we're sending. We're also specifying a regular form field called 'name'.