Using the Reddit API

Using the Using the Reddit API

Heres how to get started making API calls to Reddit.

The following is an example using PHP CURL, but any language that can make REST-API calls will work.

Step 1) Make a call the the Reddit access_token endpoint
Making a successful call to this endpoint will result in a Reddit access_token and token_type, which are then used in further API calls. Remember always store your username, password, and token in a secure non-web accessable path.
$params = array(
'grant_type' => 'password',
'username' => YourRedditUserNameHere,
'password' => YourRedditPasswordHere
);
$ch = curl_init( 'https://www.reddit.com/api/v1/access_token' );
curl_setopt( $ch, CURLOPT_USERPWD, $redditClientId . ':' . $redditClientSecret );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $params );
$redditAPI = curl_exec( $ch );
curl_close($ch);
$redditAPIdecode = json_decode($redditAPI,true); $redditToken = $redditAPIdecode['access_token']; $redditTokenType = $redditAPIdecode['token_type'];



Step 2) Make a Reddit post using the access_token and token_type obtained in step 1
$subredditName = '/r/TheSubRedditNameToPostTo';
$subredditDisplayName = 'TheDisplayNameOfTheSubreddit';
$subredditUrl = 'https://www.reddit.com/r/TheSubRedditNameToPostTo/';
$subredditPostTitle = "TitalOfTheRedditPostHere";
$apiCallEndpoint = 'https://oauth.reddit.com/api/submit';
$postData = array(
'sr' => $subredditName,
'kind' => 'self',
'title' => $subredditPostTitle,
'text' => HereIsWhereTheBodyOfYourPostGoes
);
$ch = curl_init( $apiCallEndpoint );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_USERAGENT, $subredditDisplayName . ' by /u/' . $redditUsername . ' (Phapper 1.0)' );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( "Authorization: " . $redditTokenType . " " . $redditToken ) );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );v curl_setopt( $ch, CURLOPT_POSTFIELDS, $postData );
$response_raw = curl_exec( $ch );
$redditAPIdecode = json_decode($response_raw,true);
curl_close( $ch );


You can find the Reddit endpoints, definitions, and more in the Reddit API Documentation