Tuesday, May 28, 2024

Methods to Ship "multipart/form-data" with Requests in Python

Must read


When you’ve ever wanted to ship recordsdata or knowledge to a server by way of a POST request, you have doubtless had to make use of multipart/form-data. On this Byte, we’ll see find out how to ship these requests utilizing the requests library in Python.

What’s “multipart/form-data”?

multipart/form-data is a media sort that permits you to ship binary or textual content knowledge in components inside a single request. It is usually used for issues like importing recordsdata to a server. As an example, while you add a profile image or a doc on an internet site, the information is usually despatched as multipart/form-data.

The principle benefit of multipart/form-data is its means to bundle a number of components, every with doubtlessly completely different knowledge varieties, right into a single HTTP request. That is very environment friendly and may save quite a lot of bandwidth.

Methods to Ship multipart/form-data with Requests

With regards to HTTP requests in Python, the Requests library is a go-to software. Its simplicity and performance make it standard amongst Python builders. Let’s examine how we will use it to ship multipart/form-data.

Setting Up your Setting

Earlier than we begin, be sure to have the Requests library put in. If not, you’ll be able to add it to your Python surroundings utilizing pip:

$ pip set up requests

The Code

For instance we have to add a profile image to a server. Here is a easy script that does that:

import requests

url = "http://instance.com/add"
file_path = "/path/to/your/file.jpg"

with open(file_path, "rb") as file:
    recordsdata = {'file': file}
    response = requests.submit(url, recordsdata=recordsdata)


On this script, we first import the requests library. We then outline the url the place we wish to ship the file and the file_path the place our file is positioned regionally.

We open the file in binary mode ('rb'), which permits us to learn non-text recordsdata like pictures. We then create a dictionary recordsdata the place the hot button is the string 'file' and the worth is the file object.

Lastly, we ship a POST request to the server utilizing requests.submit(url, recordsdata=recordsdata). The recordsdata parameter in requests.submit takes care of setting the Content material-Sort header to multipart/form-data.

After operating the script, it can print the standing code of the response. A standing code of 200 means the request was profitable.

Observe: Ensure to switch 'http://instance.com/add' with the precise URL you wish to ship the file to, and '/path/to/your/file.jpg' with the precise path of the file you wish to add earlier than operating this code.

Dealing with Attainable Errors

When working with multipart/form-data and Python requests, there are a couple of potential errors it is best to verify for and deal with. Python’s try-except block is the easiest way to deal with these errors.

Contemplate the next code:

import requests

url = "http://instance.com/add"
file_path = "/path/to/your/file"

    with open(file_path, "rb") as f:
        r = requests.submit(url, recordsdata={'file': f})
besides FileNotFoundError:
    print("The file was not discovered.")
besides requests.exceptions.RequestException as e:
    print("There was an exception that occurred whereas dealing with your request.", e)

This code makes an attempt to open a file and ship it as part of a multipart/form-data request. If the file doesn’t exist, a FileNotFoundError shall be raised. If requests couldn’t join, it will elevate a ConnectionError. All requests exceptions inherit from RequestException, so in our code we catch all of these errors with only one line.

Frequent Errors and Options

There are a couple of extra errors when sending multipart/form-data than what we touched on above. Let’s check out a couple of of them:

  1. requests.exceptions.TooManyRedirects: This happens when the URL you level to retains returning redirects. For instance, if two URLs redirect to one another, you may caught in an infinite loop. If requests detects this, it will elevate this exception.

  2. requests.exceptions.MissingSchema: This happens while you overlook to incorporate the protocol (http:// or https://) in your URL. Ensure your URL consists of the protocol.

  3. requests.exceptions.ConnectionError: This error is raised while you’re not in a position to connect with the server. It may very well be on account of a fallacious URL, community points, or the server may be down.

  4. requests.exceptions.Timeout: This error is raised when a request occasions out. You may deal with this by rising the timeout or setting it to None (which implies the request will wait indefinitely).

Different Strategies

One different to sending a multipart/form-data request is to make use of the http.shopper library, which is a low-level HTTP protocol shopper. It is a bit extra complicated to make use of, but it surely offers you extra management over your requests and does not require a 3rd get together library.

Here is an instance of how one can ship multipart/form-data utilizing http.shopper:

import http.shopper
import os
import uuid

# Put together the file content material
file_path = "/path/to/your/file.jpg"
with open(file_path, "rb") as f:
    file_content = f.learn()

# Outline boundary and headers
boundary = str(uuid.uuid4())
headers = {
    'Content material-Sort': f"multipart/form-data; boundary={boundary}",

# Create HTTP connection
conn = http.shopper.HTTPConnection("instance.com", 8000)

# Create multipart/form-data payload
payload = (
    f"Content material-Disposition: form-data; identify="file"; filename="file.jpg"rn"
    "Content material-Sort: textual content/plainrn"

# Ship the request
conn.request("POST", "/add", physique=payload, headers=headers)

# Get the response
response = conn.getresponse()
knowledge = response.learn()

# Shut the connection

# Print response
print(response.standing, response.purpose)

This code creates an HTTPS connection to “instance.com”, sends a POST request with our file as multipart/form-data, after which prints the response from the server.


On this Byte, you have seen find out how to ship multipart/form-data with the Python requests library, deal with potential errors, and likewise checked out some widespread errors and their options. We additionally mentioned another methodology for sending multipart/form-data utilizing http.shopper.

Supply hyperlink

More articles


Please enter your comment!
Please enter your name here

Latest article