In [1]:
import requests
base_url = 'https://www.reddit.com/'
In [2]:
# Grabbing system defined values
import os
reddit_username = 'alpscode'
reddit_password = os.environ['reddit_pass']
app_id = 'QC-6FYIEH_kqUw'
app_secret = os.environ['reddit_secret']
In [3]:
data = {'grant_type': 'password', 'username': reddit_username, 'password': reddit_password}
client_auth = requests.auth.HTTPBasicAuth(app_id, app_secret)
response = requests.post(base_url + 'api/v1/access_token',
                  data=data,
                  headers={'user-agent': 'puppy-parser by alpscode'},
                  auth=client_auth)
print(response.status_code)
values = response.json()
print(values)
200
{'access_token': '216912536673--fFzSxgNi3lkKXBvluG84vT1sLU', 'token_type': 'bearer', 'expires_in': 3600, 'scope': '*'}
In [4]:
token = 'bearer {}'.format(values['access_token'])
print(token)
bearer 216912536673--fFzSxgNi3lkKXBvluG84vT1sLU
In [5]:
api_url = 'https://oauth.reddit.com'

headers = {'Authorization': token, 'User-Agent': 'puppy-parser by alpscode'}
response = requests.get(api_url + '/api/v1/me', headers=headers)

if response.status_code == 200:
    print(response.json()['name'], response.json()['comment_karma'])

print(response.status_code)
alpscode 0
200
In [6]:
# Searching for subreddits
payload = {'q': 'puppies', 'limit': 5, 'sort': 'relevance'}
response = requests.get(api_url + '/subreddits/search', headers=headers, params=payload)
print(response.status_code)
200
In [7]:
values = response.json()
#print(response.text)
print(values.keys())
dict_keys(['kind', 'data'])
In [8]:
for i in range(len(values['data']['children'])):
    print(values['data']['children'][i]['data']['display_name'])
puppies
aww
dogpictures
corgi
lookatmydog