Ruby in reddit api

Reddit is my favorite social media platform, if we can consider it like one. It's also the only one from the old and huge platforms which still grow in popularity. I was looking a way to automate and scrap the most interesting stories from the subreddits I follow. Unfortunately, it looks like there isn't any updated gem to do the job. So I decided to read a bit of the documentation and create a sample way and here is a mini guide.

Step 1

Reddit API is currently using oauth. So you will need four things: reddit_username, reddit_password, app_id and it's secret_key. First step is to create an app or a script. There is a quick-start guide on how to do it, but it is pretty straightforward nevertheless. After you create one, you have the app_id and the secret_key.

Step 2

With these credentials you will have to do a request for an access token which lasts for 24 hours. Try a simple curl and see if you will get the access token. The curl is the following: Replace the above credentials with yours. If it succeeds, the response will be a json with the access_token. Now you will be able to use it and do all the other requests of reddit's API.

Step 3

The following code is a simple ruby script to get the access_token. There is one detail: You have to set the user-agent to something unique if you want to work. I set the user-agent to be the reddit_username. Just replace the four parameters and you are good to go:

Step 4

After that, you are now able to do the other requests. Here is an example if you want to take the latest threads from subreddit tifu, you can also pass parameters like limit etc.:

One class, a complete solution

I have written down a class for storing the access_token into a file and checking if it is still valid. I have also added some more endpoints just for tests. Here it is: Hope you found it useful, send me a message if you need any help regarding reddit API and ruby.
Max one mail per week.