API Navigator Logo

Python Requests with Multipart/Form-Data

Author: Newtum

This guide explains how to send a `multipart/form-data` request using Python Requests, which is commonly used for uploading files along with other form data.

Sending Multipart Data

To send a multipart request, you use the `files` parameter in `requests.post()`. You can include regular form fields in the `data` parameter. Requests will automatically construct the correct multipart request.

import requests
import json

# This endpoint accepts multipart form data
url = 'https://httpbin.org/post'

# Regular form data
form_data = {'user_name': 'testuser', 'user_email': 'test@example.com'}

# A dictionary for the file part.
# The tuple contains (filename, file-like-object, content-type)
# We simulate a file with a string.
files = {'report': ('report.csv', 'col1,col2\nval1,val2\n', 'text/csv')}

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

print("Status Code:", response.status_code)
# The response from httpbin.org will show the parsed form and files
print("Response JSON:")
print(json.dumps(response.json(), indent=2))