Search code examples
pythondjangopostgetpython-requests

Python How to GET Image and then POST (via requests library)


I am using python to try and get an image from one API, and then post it to a separate API.

So far I have this code:

def create_item(token, user_id):
    url = '<api_url_to_post_to>'
    headers = {"Authorization": "Token {0}".format(token)}

    image_url = '<some_random_image_url>'
    image_obj = requests.get(image_url)

    data = {
        "image": image_obj.content
    }

    r = requests.post(url, headers=headers, files=data)
    response = r.json()

    print(response)

    return response

The issue is that when I try to post it to the second API, I get a "File extension '' is not allowed." error. This is obviously a custom error message, but it signifies that there is something wrong with the file that I am posting.

Any suggestions on what I may be doing wrong?


Solution

  • Try specifying the file type, just image_obj.content is the raw binary image:

    r = requests.post(
        url, 
        headers=headers, 
        files={'image': ('my_image.jpg', image_obj.content, 'image/jpg')})
    

    This should add the correct headers to the multipart boundary for the image.

    If you don't know for sure the content type, you might actually get it from the headers of your previous response: image_obj.headers['Content-Type'] should be "image/jpg" but for a different image it might be "image/png".