In my previous post, I showed how easy it is to authenticate using the reddit API. Authenticating leaves me with an “access token”, which is just a JSON string which looks like this:

{"access_token": "261295382351-FBXDPTpUam35NR_UTJSXnjl5Pmd", "token_type": "bearer", "expires_in": 3600, "scope": "*"}

The access token gives me permission to use the reddit API. Now I can actually write an application that consumes the reddit API.

In order to motivate this demo, suppose you’re in charge of reputation management at Starbucks, and you want to be notified if anyone says anything about Starbucks at reddit. Fortunately, there’s a handy search API which can be used to search for the word Starbucks.

Here’s how you can use it to search for any mention of “Starbucks” at reddit:

curl -H "Authorization: bearer 261295382351-FBXDPTpUam35NR_UTJSXnjl5Pmd" --user-agent 'my test bot 1.0' -A "my app identifier" https://oauth.reddit.com/r/all/search?q=Starbucks

This returns a list of 25 results. If you check the search API that I linked to above, you’ll find that the default number of results (“limit”) is 25. The documentation doesn’t mention how results are sorted, but it looks like they are sorted by “relevance”, by default. We’d rather get them by “new”, to get the most recent posts. So let’s add that to the query string.

curl -H "Authorization: bearer 261295382351-FBXDPTpUam35NR_UTJSXnjl5Pmd" --user-agent 'my test bot 1.0' -A "my app identifier" https://oauth.reddit.com/r/all/search?q=Starbucks&sort=new

Now, your output is looking pretty hairy – a giant string of JSON text. You can take a look at this output in an online JSON “prettifier”, if you want to get a better idea of what’s being returned. This will be easier if your output is in a file. You can redirect the output of curl to a file. Just make sure that you put your URL in quotes, because the ampersand is interpreted by the shell to mean “start this command in the background”, which is not what you want. Do this:

curl -H "Authorization: bearer 261295382351-FBXDPTpUam35NR_UTJSXnjl5Pmd" --user-agent 'my test bot 1.0' -A "my app identifier" "https://oauth.reddit.com/r/all/search?q=Starbucks&sort=new" > data.json

Notice that so far, all I’ve done is use curl, a command line app, to call the reddit API! Now that I have a pretty good idea of how I’m going to be using the reddit API, I will start writing my Node.js application. I’ll dive into that next week.