Sending images over HTTP requests is a common task in many Python applications. The Requests library provides a simple API for attaching images and other files to POST requests.
Here's a step-by-step guide to uploading images with Requests:
1. Read the Image Data
First, load the image file and read its binary data. This converts the image to bytes that can be transmitted:
with open("image.jpg", 'rb') as f:
img_data = f.read()
2. Create the POST Request
Next, create a Requests
url = "https://api.example.com/image-upload"
headers = {"Authorization": "Client-ID xxx"}
r = requests.post(url, headers=headers)
3. Attach the Image
To add the image data to the request, use the
files = {"image": ("image.jpg", img_data)}
r = requests.post(url, headers=headers, files=files)
The first part defines the file name on the server. The second part attaches the actual image data.
Handling the Response
The API will process the uploaded image and return a response. Check the status code to see if it succeeded:
if r.status_code == 201:
print("Image uploaded successfully!")
The same pattern works for any file type like documents, videos, etc. The key is reading the binary data and attaching it with a file name to the request.
Let me know if any part needs more explanation! Uploading files via API calls is very common, so understanding the basics here will help a lot.