make a http request with a custom body as multipart form data in python

To make a HTTP request with a custom body as multipart form data in Python, we can use the requests library.

main.py
import requests

# Define the url to make the request to
url = 'http://example.com/upload'

# Define the files to be uploaded
files = {"file": ("filename", open("path/to/file", "rb"), "image/jpeg")}

# Define any additional data that needs to be uploaded
data = {"key": "value"}

# Make the request with the files and data
response = requests.post(url, files=files, data=data)

print(response.status_code)
406 chars
16 lines

In this example, we are making a POST request to http://example.com/upload with a file called filename located at path/to/file. We are also sending additional data with a key of key and a value of value.

The files parameter is used to tell requests to upload files as multipart form data, and the data parameter is used to upload any additional form data.

After the request is made, the response object will contain the server's response, including the status code and any response data.

gistlibby LogSnag