404 error when requesting json in Reddit API
Asked Answered
S

1

0

I'm trying to log into Reddit and get my own account data.

This my Python code:

from pprint import pprint
import requests
import json
username = 'dirk_b'
password = 'willnottell'
user_pass_dict = {'user': username,
      'passwd': password,
      'api_type': 'json',
      'rem': True, }
headers = {'dirkie': '/u/dirk_b API python test', }
client = requests.session()
client.headers = headers
r = client.post(r'http://www.reddit.com/api/login', data=user_pass_dict)
j = json.loads(r.content.decode());
client.modhash = j['json']['data']['modhash']
s = client.post(r'http://www.reddit.com/api/me.json', data=user_pass_dict)
pprint(s.content)

The response I get is: b'{"error": 404}'

If I do the same request without the .json part. I get a bunch of HTML code with the being 'reddit.com: page not found'. So I assume I'm doing something wrong with the URL. But the URL as I use it is how it is specified in the Reddit API.

The reason I'm not using PRAW is because I eventually want to be able to do this in c++, but I wanted to make sure it works in Python first.

Strychninism answered 22/6, 2013 at 18:55 Comment(3)
Why r.content.decode()? The json library handles the decoding for you. json.loads(r.content) is just fine; alternatively, use stream=True to client.post() and use json.load(r.raw) to have the library read from the http socket directly (may not work if the data is compressed).Cristionna
Also, what is client.modhash? That won't pass to the server.Cristionna
It does not work without .decode in 3.3 - decode() decodes it to UTF-8.Strychninism
C
3

The /api/me.json route only accepts GET requests:

s = client.get('http://www.reddit.com/api/me.json')

There is no POST route for that endpoint, so you'll get a 404 for that.

Also, if you need to pass modhash to the server, do so in the data passed in the POST request; setting client.modhash does not then pass that parameter to the server. You retrieve the modhash from your me.json GET response:

r = client.get('http://www.reddit.com/api/me.json')
modhash = r.json()['modhash']

Note how the response from requests has a .json() method, there is no need to use the json module yourself.

You then use the modhash in POST request data:

client.post('http://www.reddit.com/api/updateapp', {'modhash': modhash, 'about_url': '...', ...})
Cristionna answered 22/6, 2013 at 19:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.