Python Requests Post Zip File
If you want to post a zip file using Python requests library, it can be done easily. In my experience, I had to send a zip file to an API endpoint of a web service, and I used Python requests library to do that.
Using Requests.post()
To post a zip file using Python requests library, you can use the requests.post()
method. Here's how:
import requests
url = 'https://example.com/api/upload'
headers = {'Content-Type': 'application/zip'}
files = {'file': open('example.zip', 'rb')}
response = requests.post(url, headers=headers, files=files)
print(response.status_code)
In the above code, we first import the requests library. Then, we define the URL of the API endpoint we want to send the zip file to. The Content-Type
header is set to application/zip
to indicate that we are sending a zip file. We then define the file we want to send as a dictionary with a key 'file' and value as the open file object in binary mode.
Finally, we send the request using the requests.post()
method and print the status code of the response.
Using Requests.put()
You can also use the requests.put()
method to upload a zip file. Here's how:
import requests
url = 'https://example.com/api/upload'
headers = {'Content-Type': 'application/zip'}
with open('example.zip', 'rb') as f:
response = requests.put(url, headers=headers, data=f)
print(response.status_code)
In the above code, we open the zip file in binary mode using a with
statement. We then send the request using the requests.put()
method and print the status code of the response.
Conclusion
You can use either requests.post()
or requests.put()
method to post a zip file using Python requests library. Just make sure to set the Content-Type
header to application/zip
and define the file as a dictionary with a key 'file' and value as the open file object in binary mode.