How to get access token? (Reddit API)

末鹿安然 提交于 2019-12-03 00:37:09

As of right now, you cannot retrieve a permanent access token. You have 2 options that come close.

The first is to request a "refresh" token when using the standard OAuth flow. That's what you're doing by sending "duration" as "permanent" in your code. The refresh token can be used to automatically retrieve new 1 hour access tokens without user intervention; the only manual steps are on the initial retrieval of the refresh token.

The second alternative, which applies only when writing a script for personal use, is to use the password grant type. The steps are described in more detail on reddit's "OAuth Quick Start" wiki page, but I'll summarize here:

  1. Create an OAuth client (under https://www.reddit.com/prefs/apps) with type = "script"
  2. Make a request to https://www.reddit.com/api/v1/access_token with POST parameters grant_type=password&username=<USERNAME>&password=<PASSWORD>. Send your client ID and secret as HTTP basic authentication. <USERNAME> must be registered as a developer of the OAuth 2 client ID you send.
AlexG

A client_id and client_secret can be generated for a reddit account by going to https://www.reddit.com/prefs/apps and creating an app:


The part I have hidden is my client_id.

Then you can use a client like praw to access reddit e.g. with Python:

import praw
r = praw.Reddit(client_id='insert id here',
                client_secret='insert secret here',
                user_agent='insert user agent')
page = r.subreddit('aww')
top_posts = page.hot(limit=None)
for post in top_posts:
    print(post.title, post.ups)

You could use your current browser's user agent, which can be easily found by google searching "what is my user agent" (among other ways).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!