Submitting POST Request with Image

Question:

I’m trying to do my first POST request (on TinEye) that involves uploading an image. I’m trying to piece together bits from these answers: Python POST Request with an Image , How to post image using requests? , Sending images by POST using python requests , and Sending image over POST request with Python Requests , but I’m still missing something.

The headers of the request looks like this:
headers1:
headers1
headers2:
headers2

(…not sure what identifying info, if any, there are in there so I’ve blocked them just in case)

And the payload looks like this:
payload:
payload

So, with all this info, what I’ve attempted so far looks like this:

import requests
import random,string
# pip install requests_toolbelt
from requests_toolbelt import MultipartEncoder

image_filename = "2015_Aston_Martin_DB9_GT_(19839443910).jpg" # Change this to another filename
imported_image = open(image_filename, 'rb')

def submit_image_post_request(image):
    # Create a get request to get the initial cookies
    cookies = requests.get("https://tineye.com/").cookies
    
    # Generate a WebKitFormBoundary
    boundary = '----WebKitFormBoundary' + ''.join(random.sample(string.ascii_letters + string.digits, 16))
    
    # Generate the headers
    headers = {
        'authority': 'tineye.com',
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'en-US,en;q=0.9',
        'content-type': 'multipart/form-data; boundary=' + boundary,
        'origin': 'https://tineye.com',
        'referer': 'https://tineye.com/search/c8570370e2b2338dc656c8cefe221655b8a0ca17?sort=score&order=desc&page=1',
        'sec-ch-ua': '"Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
    }
    
    # Give the params
    params = {
        'sort': 'score',
        'order': 'desc',
    }

    # Now comes the experimenting.
    # Define a 'files' variable for the request using the opened image file
    files = {
        'image': image
    }
    
    # Try to recreate the "fields" of the form/request
    fields = {
        'file': (image_filename, image, "image/jpeg"),
        # 'file_id': "0"
        # "Content-Disposition": 'form-data; name="image"; filename=image_filename'
    }

    # Generate a MultipartEncoder using the fields and same boundary as in the headers
    m = MultipartEncoder(fields=fields, boundary=boundary)
    
    # Send the request
    response = requests.post('https://tineye.com/result_json/', params=params, headers=headers, files=files, cookies=cookies, data=m)
    
    return response

response = submit_image_post_request(imported_image)

It’s not working obviously, I get a 400 response currently, and it’s because of the last little bit of the function, as I’m not quite sure how to recreate the request. Looking to get some guidance on it.

Asked By: windowshopr

||

Answers:

I found an article that showed how to copy the request as a curl from Chrome, import it into Postman, and then export the corresponding python request from Postman, which I have done below as an updated attempt at got the 200 response code. Woohoo!

    def search_image(self, image):
        
        url = "https://tineye.com/result_json/"
        
        cookies = requests.get(url).cookies

        payload={}
        files=[
        ('image',('file', image,'application/octet-stream'))
        ]
        headers = {
        'authority': 'tineye.com',
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'en-US,en;q=0.9',
        # 'cookie': '_ga=GA1.2.1487505347.1661754780; sort=score; order=desc; _gid=GA1.2.613122987.1662166051; __cf_bm=VYpWBFxDJVgFr_e6N_51uElQ4P0qmZtysVNuPdG4MU4-1662166051-0-AQ3g7/Ygshplz8dghxLlCTA8TBrR0b+YXr9kOMfagi18Ypry9kWkDQELjUXOGpClZgoX/BjZExzf+3r6aL8ytCau2kM8z5u3sFanPVaA39wOni+AMGy69RFrGBP8om+naQ==; tineye=fz1Bqk4sJOQqVaf4XCHM59qTFw8LSS6aLP3fQQoIYLyVWIsQR_-XpM-E6-L5GXQ8eex1ia7GI0-ffA57yuR-ll0nfPeAPkDzqdp1Uw; _gat_gtag_UA_2430070_8=1',
        'origin': 'https://tineye.com',
        'referer': 'https://tineye.com/search',
        'sec-ch-ua': '"Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'
        }

        response = requests.post(url, headers=headers, data=payload, files=files, cookies=cookies, timeout=60)
        return response
Answered By: windowshopr
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.