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:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: