python requests post binary data

Python Requests Post Binary Data

Python Requests library is a powerful tool to make HTTP requests. It supports various HTTP methods such as GET, POST, PUT, DELETE, etc. In this answer, we will focus on how to use the Requests library to send POST requests with binary data.

Using the Requests Library to Post Binary Data

The Requests library allows us to send a POST request with binary data using the data parameter. The binary data can be anything from an image to a PDF file.


import requests

url = 'https://example.com/upload'
binary_data = open('file.pdf', 'rb') # opening the file in read binary mode

response = requests.post(url, data=binary_data)

print(response.status_code) # prints 200 if the upload was successful
    

In the above code, we first import the Requests library and define the URL to which we want to send the POST request. We then open the binary file in read binary mode using the open() function and pass it to the data parameter of the requests.post() method.

Finally, we print the status code of the response to check if the upload was successful.

Using Multipart-Encoded Requests

Another way to send binary data is by using multipart-encoded requests. This method is useful when we want to send multiple files or data along with the binary file.


import requests

url = 'https://example.com/upload'
files = {'file': open('file.pdf', 'rb')}

response = requests.post(url, files=files)

print(response.status_code) # prints 200 if the upload was successful
    

In the above code, we define the URL and create a dictionary with the key 'file' and the binary file opened using the open() function in read binary mode. We then pass this dictionary to the files parameter of the requests.post() method.

Finally, we print the status code of the response to check if the upload was successful.