Reddit Authentication & Access tokens

Reddit API

For this section, I will be using the Reddit API to perform CRUD on my own subreddit - r/tom_land. Reddit generously offers an API to perform almost all user actions on their site, from scraping posts to moderator duties.

Reddit, though, specify in their documentation that users must be authenticated using Oauth to make requests to the API. Oauth is a authentication system which grants access to particular individuals or groups typically using a client ID / secret key combination. This pair is essentially a username and password to access resources on Reddit. Once sent to the server, it knows that you are authorized to access resources, and grants an access token so you can do so.

Upon signing up to use the Reddit API, and stating your application is not for commercial purposes, you are supplied with your client ID, and secret key. After making a few test posts on my subreddit, I was ready to start accessing Tom Land. 


To begin with, once the document is ready my provided ID and secret are placed in to variables to be used in the request for an access token.

To be granted an access token, I am making an AJAX post request to the access token URL, with my ID and secret as headers, indicated in the 'xhr.setReqeustHeader()' method. These are encoded in base 64 by the btoa() function, which is required by Reddit.

The data being sent in the request includes the grant_type, which is set to password, which is required for requests such as create, edit, and delete. This type requires your Reddit Username and Password too, as you must be logged in as the subreddit moderator for subreddit functionality.

Once that ajax request is successful, another is run subsequently to retrieve subreddit posts using the URL https://oauth.reddit.com/r/tom_land. The preface 'oauth' is an area of resources only accessable when authenticated using the Reddit oauth system.


Like before, we must attach some variables to the header, in this case, the variables are the token type, which is password, and the access token itself. These together are used to access resources.

If this GET request is successful, it returns ALL data regarding the subreddit such as time of creation, flairs, members etc. What we are interested in, though, are the posts. Each post is returned with all its data and metadata. Using a for loop we can loop through each post and print out the title and description which is appended to the <posts> tag in the html.

The application ends up looking like this:


And this is mirrored in the subreddit itself:


Next I will attempt to create a new post on my subreddit using the Reddit API.

Comments

Popular posts from this blog

Creating a Reddit post

Deleting a Reddit Post