Wednesday, September 20, 2023
HomeProgrammingThe way to Ship "multipart/form-data" with Requests in Python

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


When you’ve ever wanted to ship information or knowledge to a server through a POST request, you have seemingly had to make use of multipart/form-data. On this Byte, we’ll see methods to ship these requests utilizing the requests library in Python.

What’s “multipart/form-data”?

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

The primary benefit of multipart/form-data is its means to bundle a number of components, every with probably totally different knowledge sorts, right into a single HTTP request. That is very environment friendly and might save numerous bandwidth.

The way to Ship multipart/form-data with Requests

In relation 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 you 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

As an example we have to add a profile image to a server. Here is a easy script that does that:

import requests

url = ""
file_path = "/path/to/your/file.jpg"

with open(file_path, "rb") as file:
    information = {'file': file}
    response = requests.put up(url, information=information)


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 information like photographs. We then create a dictionary information 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.put up(url, information=information). The information parameter in requests.put up takes care of setting the Content material-Sort header to multipart/form-data.

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

Word: Be sure that to exchange '' 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 number of potential errors it’s best to verify for and deal with. Python’s try-except block is one of the simplest ways to deal with these errors.

Contemplate the next code:

import requests

url = ""
file_path = "/path/to/your/file"

    with open(file_path, "rb") as f:
        r = requests.put up(url, information={'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 can be raised. If requests couldn’t join, it’s going to increase a ConnectionError. All requests exceptions inherit from RequestException, so in our code we catch all of these errors with only one line.

Widespread Errors and Options

There are a number of extra errors when sending multipart/form-data than what we touched on above. Let’s check out a number 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 will caught in an infinite loop. If requests detects this, it’s going to increase this exception.

  2. requests.exceptions.MissingSchema: This happens once you neglect to incorporate the protocol (http:// or https://) in your URL. Be sure that your URL contains the protocol.

  3. requests.exceptions.ConnectionError: This error is raised once you’re not in a position to connect with the server. It may very well be as a consequence of a unsuitable URL, community points, or the server is likely to be down.

  4. requests.exceptions.Timeout: This error is raised when a request instances out. You possibly can deal with this by growing the timeout or setting it to None (which suggests 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’s kind of extra advanced to make use of, however it offers you extra management over your requests and would not require a 3rd celebration 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("", 8000)

# Create multipart/form-data payload
payload = (
    f"Content material-Disposition: form-data; title="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.motive)

This code creates an HTTPS connection to “”, 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 methods to ship multipart/form-data with the Python requests library, deal with potential errors, and in addition checked out some frequent errors and their options. We additionally mentioned an alternate technique for sending multipart/form-data utilizing http.shopper.



Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments