Search code examples
pythonoauthimgur

Retroactively passing token information, after receiving it from the Imgur API using requests-oauth


I'm new to using any API, as well as HTTP requests, so I'm having some trouble. I'm not sure how to pass token information to the API, after I get it from a GET request. The imgur API says it needs the three endpoints: http://api.imgur.com/auth but I only get as far as the second one, because I'm not able to pass the requested tokens in.

The modules documentation is awfully vague to me about it: https://github.com/maraujop/requests-oauth

Here's the code I've written that is supposed to pass authentication successfully, but it returns an html page http://pastebin.com/19hnBy1C.

import requests
from oauth_hook import OAuthHook
import cgi

OAuthHook.consumer_key = 'XXXXXXX'
OAuthHook.consumer_secret = 'YYYYY'


#just in case
oauth_hook = OAuthHook(header_auth=True)

#request the tokens, using the keys set above
r = requests.get(url='https://api.imgur.com/oauth/request_token', hooks={'pre_request': oauth_hook,})

#parse the lsit
tokenList = cgi.parse_qs(r.content)

token = tokenList['oauth_token']
tokenSecret = tokenList['oauth_token_secret']

#this is where I'm not sure what to do, 
#I create a new hook with the tokens I received
oauth_hook = OAuthHook(access_token=token[0], access_token_secret=tokenSecret[0])

#send the GET request
r = requests.get(url='https://api.imgur.com/oauth/authorize', hooks={'pre_request': oauth_hook,})

#this is that HTML that requires me to enter account info, how do I do that in python?
print r.content

#this is the next step, which, if you uncomment the last print, shows that the auth failed.
r = requests.get(url='https://api.imgur.com/oauth/access_token', hooks={'pre_request': oauth_hook,})

#print r.text

What is the best way to continue?

I thought maybe that I could send a POST to the authorize api, with my username/password as a data or a parameter, but that didn't seem to work.

The Imgur API suggests I look at some twitter docs to get a good idea, but the one I'm reading: http://net.tutsplus.com/tutorials/php/how-to-authenticate-users-with-twitter-oauth/ , is a bit over my head, since it's PHP, though it seems like it is what I should be doing.


Solution

  • I'm the author of requests-oauth. I've recently released version 0.4.0 of this app and improved docs for helping new comers to OAuth.

    Here, hopefully, is the answer to your question: https://github.com/maraujop/requests-oauth#3-legged-authorization

    Sorry to take so long to answer.