Project: Reddit API using OAuth


Questions to address:

  • access reddit via API
  • get data on a given subredit and find the most upvoted commnent
  • upvote a comment


Tools:

  • requests
  • authenticate access via requests.auth.HTTPBasicAuth
  • get data: response = requests.get()
  • post data: response = requests.post

Authenticate Reddit OAuth

In [2]:
import requests
import requests.auth
client_auth = requests.auth.HTTPBasicAuth('foo', 'bar')
post_data = {"grant_type": "password", "username": "user", "password": "pass"}
headers = {"User-Agent": "RedditUser"}
authentication = requests.post("https://www.reddit.com/api/v1/access_token", auth=client_auth, data=post_data, headers=headers)


Dataset: comments on the python/top reddit

In [6]:
token = "bearer "+authentication.json()['access_token']
headers = {"Authorization": token, "User-Agent": "user"}
params = {"t": "day"}
response = requests.get("https://oauth.reddit.com/r/python/top", headers=headers, params=params)

python_top = response.json()


Analysis:


find the ID of the most upvoted comment

In [7]:
children = python_top['data']['children']

python_data=[]
for element in children:
    python_data.append(element['data'])
    
#print(python_data)    
    
python_top_articles = [] 
most_upvoted_votes = 0
for element in python_data:
    python_top_articles.append(element['title'])
    if(element['ups']>most_upvoted_votes):
        most_upvoted_votes=element['ups']
        most_upvoted=element['id']
        
print(most_upvoted)
9reap0


retrieve all comments associated with that post and find the most upvoted top-level comment in comments

In [9]:
response = requests.get('https://oauth.reddit.com/r/python/comments/9o3x81', headers=headers)
comments = response.json()

comments_list = comments[1]['data']['children']
#print(comments_list)

most_voted = 0

for element in comments_list:
    data = element['data']
    if(data['ups']>most_voted):
        most_voted = data['ups']
        most_upvoted_comment = data #['id']
print(most_upvoted_comment['body'])    
This is going to come in handy, thanks!


upvoat a comment

In [ ]:
payload = {"dir": 1, "id": "d16y4ry"}
headers = {"Authorization": token, "User-Agent": "RedditCDMal"}
response = requests.post('https://oauth.reddit.com/api/vote',headers=headers,json=payload)
print(response.status_code)