How to send a multipart/form-data with requests in python?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Sending multipart/form-data with Python requests is the standard way to upload files alongside text fields. The library handles boundary generation automatically when you use the files argument correctly. Most issues come from incorrect payload shape, file handle management, or mixing JSON with multipart semantics.
Basic File Upload
Simple one-file upload:
requests sets proper multipart content type automatically.
Multiple Files in One Request
Use list of tuples for repeated field names.
Remember to close file handles or use context managers for each file.
Raw Bytes Upload Without Disk File
You can upload generated bytes content.
Useful for generated reports or transformed content.
Authentication and Headers
Keep auth separate from multipart construction.
Do not manually set Content-Type to multipart with custom boundary unless you build body yourself.
Error Handling and Retries
Add timeout and handle transport failures.
For critical workflows, add retry with backoff for transient errors.
Server Expectations
Server frameworks may require specific field names:
- file field key such as
fileorattachments - metadata field names exactly matching backend parser
Always check API docs and inspect server error payloads if upload fails.
Sending File and JSON Metadata Together
Multipart requests carry text fields as form values, not JSON body.
Server can parse meta field as JSON string.
Streaming Large Uploads
For very large files, monitor memory and network timeouts. Keep chunked upload or resumable APIs in mind when simple multipart calls are insufficient for production limits.
Session Reuse and Connection Hygiene
Reuse a requests.Session for repeated multipart uploads to reduce connection overhead.
Server-Side Debugging Tip
If upload returns validation errors, inspect server expectation for field names and multipart parser configuration. Most failures are contract mismatches rather than transport issues.
Document this pattern for team consistency.
Validate with realistic test cases before deployment.
Log request ids for traceability.
Test thoroughly.
Consistently.
Use retries.
Common Pitfalls
- Sending file path string instead of opened binary file.
- Manually overriding multipart content type headers incorrectly.
- Forgetting to include text fields in
dataalongsidefiles. - Leaking file handles by not closing opened files.
- Assuming JSON body and multipart body can be combined as one payload format.
Summary
- Use
filesanddatainrequests.postfor multipart uploads. - Let
requestsgenerate multipart boundaries automatically. - Manage file handles safely with context managers.
- Include proper timeout and error handling for reliability.
- Match server field names and authentication expectations precisely.

