uploading a file to imgur via python
Asked Answered
E

1

7

I'm having trouble uploading an image to Imgur using the python requests module and the Imgur API.

My code is the following:

import base64
import json
import requests

from base64 import b64encode

client_id = 'my-client-id'

headers = {"Authorization": "Client-ID my-client-id"}

api_key = 'my-api-key'

url = "http://api.imgur.com/3/upload.json"

j1 = requests.post(
    url, 
    headers = headers,
    data = {
        'key': api_key, 
        'image': b64encode(open('1.jpg', 'rb').read()),
        'type': 'base64',
        'name': '1.jpg',
        'title': 'Picture no. 1'
    }
)

I usually get a 400 response error. I'm not sure if myu client_id is wrong, or if my request is wrong (I have very little experience on url requesting), or if I'm using the Imgur API wrong.

I'd also like to get the url of the image once I have submitted this. I'm not sure if the API has a command for that, or if the python.requests module has a trick that can let me GET the data I just posted(POST).

A very similar question was answered here, and the code actually worked!: Trouble sending a file to Imgur

However when I used my client_id, insted of the application ID that was used in the code, it returned a 400 error, as well as when I changed

from: url = "http://api.imgur.com/2/upload.json" to: url = "http://api.imgur.com/3/upload.json"

Ellingston answered 26/4, 2013 at 19:52 Comment(0)
P
9

This is a v3 request, but you're not using SSL, which is mandatory. Try setting

url = "https://api.imgur.com/3/upload.json"
#          ^
Philomel answered 26/4, 2013 at 19:55 Comment(3)
Thanks! that did the trick! The request proceeded, but I can't manage to get the URL hash of the image I just posted. Do you know how I should do this?Ellingston
@Mecasickle, you can get all information in body of response. Just add to your code same as: data = json.loads(j1.text)['data']; print data['link'], data['id'], data['deletehash'] `Euchology
Alright, this is done. Now I'm trying to get it on the gallery. Here's the link api.imgur.com/models/gallery_imageEllingston

© 2022 - 2024 — McMap. All rights reserved.