Uploading Images with Python Requests

Feb 3, 2024 ยท 2 min read

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 POST request object. Set the URL to upload the image to and add any headers or other parameters:

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 parameter. This uploads the image with a file name:

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.

Browse by tags:

Browse by language:

Tired of getting blocked while scraping the web?

ProxiesAPI handles headless browsers and rotates proxies for you.
Get access to 1,000 free API credits, no credit card required!