Python
Multipart Form Data
HTTP Requests
Requests Library
Programming Tutorial

How to send multipart/form-data with requests in Python

Codemia Knowledge Hub ·

Pass files through the files argument of requests.post and plain text fields through data. requests then builds the multipart/form-data body and generates the boundary automatically. Most problems come from the wrong payload shape, leaked file handles, or mixing JSON with multipart.

Upload a single file

python
1import requests
2
3url = "https://httpbin.org/post"
4
5with open("report.pdf", "rb") as f:
6    files = {"file": ("report.pdf", f, "application/pdf")}
7    data = {"user_id": "42", "category": "finance"}
8    resp = requests.post(url, files=files, data=data, timeout=30)
9
10print(resp.status_code)
11print(resp.json()["files"].keys())

requests sets the multipart content type for you.

Upload multiple files in one request

Use a list of tuples when the same field name repeats:

python
1files = [
2    ("attachments", ("a.txt", open("a.txt", "rb"), "text/plain")),
3    ("attachments", ("b.txt", open("b.txt", "rb"), "text/plain")),
4]
5
6resp = requests.post(url, files=files, data={"ticket": "123"})

Close each file handle, or open each file in a context manager.

Upload raw bytes without a file on disk

You can upload bytes generated in memory, which is useful for generated reports or transformed content:

python
content = b"hello from memory"
files = {"file": ("memory.txt", content, "text/plain")}
resp = requests.post(url, files=files)

Add authentication headers

Keep auth headers separate from the multipart construction:

python
headers = {"Authorization": "Bearer TOKEN"}
resp = requests.post(url, headers=headers, files=files, data=data)

Do not set Content-Type to multipart with a custom boundary yourself unless you also build the body yourself. Overriding it incorrectly breaks the upload.

Handle errors and timeouts

Set a timeout and catch transport failures:

python
1import requests
2from requests.exceptions import RequestException
3
4try:
5    resp = requests.post(url, files=files, data=data, timeout=20)
6    resp.raise_for_status()
7except RequestException as exc:
8    print("upload failed:", exc)

For critical workflows, add retries with backoff for transient errors.

Send a file with JSON metadata

Multipart requests carry text fields as form values, not as a JSON body, so you cannot combine a JSON body and a multipart body in one payload. Serialize the metadata into a form field instead:

python
1import json
2
3meta = {"source": "mobile", "priority": "high"}
4files = {"file": ("img.png", open("img.png", "rb"), "image/png")}
5data = {"meta": json.dumps(meta)}
6
7resp = requests.post(url, files=files, data=data)

The server can then parse the meta field as a JSON string.

Reuse a session for repeated uploads

A requests.Session reduces connection overhead across repeated multipart uploads:

python
1session = requests.Session()
2with open("report.pdf", "rb") as f:
3    files = {"file": ("report.pdf", f, "application/pdf")}
4    r = session.post(url, files=files, timeout=30)

Large files

For very large files, watch memory use and network timeouts. If a simple multipart call cannot meet production limits, consider chunked or resumable upload APIs.

When the server rejects the upload

Most failures are contract mismatches, not transport issues. Check:

  • the file field key the server expects, such as file or attachments
  • that metadata field names exactly match the backend parser
  • that you sent an opened binary file, not a file path string
  • that text fields are in data alongside files

Read the API docs and inspect the server's error payload. Logging request IDs helps trace failed uploads.


Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design