Uploading Files Through Multipart Form Data
In this lesson, you will learn how to transmit binary files alongside standard text form fields by manually configuring multipart/form-data requests.
When you need to send a file to a server—like uploading an image profile or a configuration document—a standard JSON payload won't suffice because binary data cannot be natively embedded as a raw string. Instead, we use multipart/form-data. This encoding format breaks the request body into distinct "parts," each separated by a unique boundary string, allowing you to bundle metadata (like a user ID) and binary streams (the file) in a single HTTP request.
While the requests library often handles this automatically when you pass a files dictionary, understanding the underlying structure is vital for advanced API integration where you must explicitly define Content-Type headers or process streams.
Implementing Multipart Uploads
To perform a multipart upload, you define a dictionary where the keys match the field names expected by the server. When you open a file in binary mode ('rb'), the requests library automatically sets the Content-Type header to multipart/form-data and calculates the necessary boundary for you.
import requests
url = "https://api.example.com/upload"
data = {"user_id": "12345"}
# Open the file in binary mode
with open("report.pdf", "rb") as f:
# The 'files' parameter handles the binary encoding
files = {"document": ("report.pdf", f, "application/pdf")}
# The library automatically appends the boundary to the Content-Type header
response = requests.post(url, data=data, files=files)
response.raise_for_status()
print("Upload successful!")
The files dictionary uses a tuple: (filename, file_object, content_type). This explicit declaration ensures that even if your file lacks a standard extension, the server correctly identifies the incoming stream as a specific media type. If you were building this manually for a custom service, you would need to define the multipart boundary yourself and ensure the Content-Type header includes that boundary string, but by leveraging the files argument, Python manages the lifecycle and closing of the binary stream for you.
Key Takeaway: Multipart form data encapsulates binary files and text fields into a single request body using boundary-delimited segments, ensuring servers can distinguish between metadata and file streams.