Sending Multipart Form Data with Python Requests

Feb 3, 2024 ยท 2 min read

When building web applications in Python, you may need to send multipart form data in an HTTP request. This allows you to upload files and send other form data to a server endpoint.

However, you may run into issues properly formatting the request in the Python requests library. Here are some troubleshooting tips for sending multipart form data with Requests.

Structuring the Request Correctly

To send a multipart form request with Requests, you need to create a dict containing the form fields, and a files dict with any file uploads. For example:

import requests

url = 'https://api.example.com/upload'

data = {
  'description': 'My File',
  'extra': 'Some extra data' 
}

files = {
  'file_upload': open('report.pdf', 'rb')
}

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

Note the file is opened in binary mode with 'rb', and added to the files parameter separately.

Handling Network Errors

Sometimes the request fails due to network issues. You should catch exceptions and handle them appropriately:

try:
  r = requests.post(url, data=data, files=files)
except requests.exceptions.RequestException as e:  
  print(e)

This will print the specific error that occurred.

Summary

  • Structure multipart form requests with a data dict and files dict
  • Open files to upload in binary 'rb' mode
  • Use try/catch to handle network errors
  • With these tips, you can properly structure multipart form data requests in Python and handle issues as they arise. The Requests library handles most of the complexity behind the scenes.

    Browse by tags:

    Browse by language:

    Tired of getting blocked while scraping the web?

    ProxiesAPI handles headless browsers and rotates proxies for you.
    Get access to 1,000 free API credits, no credit card required!