403 error while calling Reddit API.

2019-05-25 08:34发布

问题:

I'm trying to access data saved by the user. And it keeps returning a 403 error with this being its api end point.

http://www.reddit.com/dev/api#GET_user_{username}_saved

I'm thoroughly confused what to send in my headers to make this request work and the reddit documentation has no mention of it at all. Help?

I'm using Python-requests library to do this.

回答1:

Referring to line 686 in reddit's code in listingcontroller.py (here) :

    if (where in ('saved', 'hidden') and not 
        ((c.user_is_loggedin and c.user._id == vuser._id) or
          c.user_is_admin)):
        return self.abort403()

you can clearly see that you must be logged in as username or be an admin in order to get the saved or hidden data - otherwise you get a 403 error.



回答2:

As @zenpoy already mentioned (and which you already know), you have to be logged in. Therefore, you should save the cookie, which you get as a response of a valid call to api/login. I've written some code, which logs a user in and retrieves all saved things:

import urllib
import urllib2
import cookielib
import json

login_url = 'https://ssl.reddit.com/api/login/'
saved_url = 'https://ssl.reddit.com/user/<username>/saved.json'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))


def login(username, passwd):
    values = {'user': username,
              'api_type': 'json',
              'passwd': passwd}

    data = urllib.urlencode(values)
    response = opener.open(login_url, data).read()

    print json.loads(response)


def retrieve_saved(username):
    url = saved_url.replace('<username>', username)
    response = opener.open(url).read()

    print json.loads(response)


login(<username>, <passwd>)
retrieve_saved(<username>)


标签: python reddit