Friday, February 10, 2017

Taming the Snoo: Playing with the Reddit API

Reddit is a social networking, entertainment, and news website where the content is almost exclusively submitted by users. According to this report, in February 2016 Reddit had 36 million user accounts, 231 million unique monthly visits, and 11.464 active communities. A recent study also showed that 80% of Reddit users get their news from there.

Reddit also offers its own API. This way, we can use all the information available on Reddit to enrich our own websites or build our own Reddit clients. In this article, we will tackle some basic Reddit API usage with PHP.

Realistic Reddit Alien Painting

The Reddit API

The Reddit API is extensive and very well documented, from private methods that are only accessible through authentication (Reddit uses OAuth2), to public methods that we can use with a basic HTTP call.

In this article, we'll first focus on the search method. While this is a public call (it does not require authentication), it is also one of the most powerful ones, since it allows us to access all of the history of Reddit posts in every subreddit.

The search method

The search method is available through a basic HTTP request and has a lot of properties. Looking at the documentation, we can see that it supports the HTTP GET method and is available through

http://ift.tt/2kQDSbz

We also have the following arguments available: after, before, count, include_facets, limit, q, restrict_sr, show, sort, sr_detail, syntax, t, and type. The table below can be found in the documentation, and shows every argument with more detail.

Argument Receives
after full name of a thing
before full name of a thing
count a positive integer (default: 0)
include_facets boolean value
limit the maximum number of items desired (default: 25, maximum: 100)
q a string no longer than 512 characters
restrict_sr boolean value
show (optional) the string all
sort one of (relevance, hot, top, new, comments)
sr_detail (optional) expand subreddits
syntax one of (cloudsearch, lucene, plain)
t one of (hour, day, week, month, year, all)
type (optional) comma-delimited list of result types (sr, link)

We will focus on the q, limit, sort and restrict_sr arguments.

The q argument is the most important one and indicates the query for which we will search the subreddit in question. An example of usage would be:

http://ift.tt/2l1OPZY

This particular call will search for the oop expression in the php subreddit. If you try to make the call using your browser, you will see the results (just copy and paste the link in your browser).

The limit argument limits the number of posts that the returned list will have. An example of usage would be:

http://ift.tt/2kQpjEF

This particular search would return the first 5 results of searching for the oop expression in the php subreddit.

Continue reading %Taming the Snoo: Playing with the Reddit API%


by Claudio Ribeiro via SitePoint

No comments:

Post a Comment