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.

Revisions

  1. redknight99 created this gist Nov 15, 2019.
    41 changes: 41 additions & 0 deletions simple_python_reddit_api_example.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    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()) )