Skip to content

Instantly share code, notes, and snippets.

@redknight99
Created November 15, 2019 00:40
Show Gist options
  • Save redknight99/acf91ef1409cf50c089e8283c9212333 to your computer and use it in GitHub Desktop.
Save redknight99/acf91ef1409cf50c089e8283c9212333 to your computer and use it in GitHub Desktop.
Background: I recently ran into headaches trying to get the Reddit API to work for a simple non-PRAW Python script. So I adapted this together from the https://github.com/reddit-archive/reddit/wiki/OAuth2-Quick-Start-Example for future reference.
import requests
import requests.auth
"""
This is a simple non-PRAW Reddit API example using Python and the Python module Requests.
SECURITY NOTE: client_token, client_secret, password, username, accesss_token are all taken from the URL:
https://github.com/reddit-archive/reddit/wiki/OAuth2-Quick-Start-Example and should be
be replace by your own.
"""
# You'll find your client secret and client token at reddit.com/prefs/apps
client_token = 'p-jcoLKBynTLew'
client_secret = 'gko_LXELoV07ZBNUXrvWZfzE3aI'
client_auth = requests.auth.HTTPBasicAuth(client_token, client_secret)
password = "snoo"
username = "reddit_bot"
post_data = {"grant_type": "password", "username": username, "password": password}
headers = {"User-Agent": "ChangeMeClient/0.1 by YourUsername"}
response = requests.post("https://www.reddit.com/api/v1/access_token", auth=client_auth, data=post_data, headers=headers)
# We're just assuming that we got a HTTP 200 response from auth
# Anyone using this should implement their own error handling.
print("The response we got was: " + str(response.json()) )
"""
Response should be something like:
{u'access_token': u'fhTdafZI-0ClEzzYORfBSCR7x3M',
u'expires_in': 3600,
u'scope': u'*',
u'token_type': u'bearer'}
"""
access_token = "bearer " + str(response.json()["access_token"])
headers = {"Authorization": access_token, "User-Agent": "ChangeMeClient/0.1 by YourUsername"}
response = requests.get("https://oauth.reddit.com/api/v1/me", headers=headers)
print("The response we got was: " + str(response.json()) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment