w3resource

Twitter REST API Tutorial

Introduction

Twitter REST API allows you to retrieve tweets and related information from Twitter. This tutorial will unleash how to get started with Twitter REST API. We will work with Twitter REST API V1.1

Obtain Keys

Point your browser to http://apps.twitter.com, login with your Twitter username and password and then from the dropdown menu under your username, click on create a new application.

Create an Application - twitter REST API

After you fill the details required here and hot submit, you will end up with following.

Application Settings - twitter REST API

You also need to generate Access keys from this page.

Download Authentication library

Download Twitter API authentication library from Github with the following command.

git clone https://github.com/abraham/twitteroauth.git

Creating a application

Following code is used to create the application(in PHP).

<?php
session_start();
require_once("twitteroauth/twitteroauth/twitteroauth.php"); //Path to twitteroauth library you downloaded in step 3

$twitteruser = "w3resource"; //user name you want to reference
$notweets = 2; //how many tweets you want to retrieve
$consumerkey = "sqrzNfTYAhdKKFe8i0jkbmfJc";
$consumersecret = "UY4UiIjYTuB4Z09Kh5ZeC8nA1M9rPT9VNNutZa8wPivVCj6SoV"; 
$accesstoken = "217674868-6jGUXSmNd1ldEgPm19Ms0sOVd1NWHlqOPOvDjD1Z"; 
$accesstokensecret = "KehU1HYSmeo5JrNhlWbPrqXPaVWJMr2gi72UINuaDAufQ"; 

function getToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
  $connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
  return $connection;
}

$connection = getToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);

echo json_encode($tweets);
//echo $tweets; //testing remove for production   
?>

Make sure your filename is the same as you mentioned in the url name when you created API keys for your application.

You may view the live demo of the application here.

Previous: Get the top artists and their playcounts with last.fm API
Next: Jquery plugins for Twitter API



Follow us on Facebook and Twitter for latest update.