Javascript Programming For Twitter API 1.1: by Adam Green
Javascript Programming For Twitter API 1.1: by Adam Green
Programming
For Twitter API 1.1
By Adam Green
CEO, 140dev.com
Javascript
Programming
for Twitter API 1.1
Adam Green
Lexington, Massachusetts
Javascript programmers have to change their basic way of coding when they switch to Twitter
API 1.1. With API 1.0 your web page could make an Ajax request directly from Twitter with a
callback argument. The response would come back as JSON or XML, which you could parse and
then display on the web page. API 1.1 breaks all of that Javascript code.
With version 1.1 you have to make an OAuth connection to the API before any requests, and I
do mean any. That includes getting a user’s timeline or even the Twitter home timeline. Twitter
search in API 1.1 also requires OAuth. In addition, all RSS feeds from Twitter will be turned off
with API 1.1. They too will have to be replaced by code that uses OAuth. Twitter says that
version 1.0 will be shut down in March, so it is time to convert your code
Twitter isn’t doing this to be mean or evil. Twitter API 1.1 is still free, and it increases many of
the rate limits. The problem has been that API 1.0 didn’t give Twitter any control over who was
grabbing huge quantities of data. The most Twitter could do was block an entire IP address
from any access, which is crude and often punishes the innocent on shared servers. The OAuth
requirement in API 1.1 allows Twitter to monitor and control who is using the API down to an
individual user. That seems fair in return for free access to so much useful data.
As a result, making a direct connection from Javascript to the Twitter API is effectively turned
off as a viable programming technique. Kind of sad, but things change and we have to move on.
Multi-user OAuth allows you to connect to any Twitter account to make changes, but you have
to set up a user interface on your website that allows users to log into Twitter. You also have to
keep track of which user has already authorized your Twitter app, and get their OAuth tokens
for each API request. These programming techniques are beyond the scope of this short ebook.
We’ll limit ourselves to single-user OAuth here.
The particular style of single-user OAuth coding used here is documented in a separate free
ebook available on my 140dev.com website. It uses the tmhOAuth library, which is also free,
and the PHP language, and that’s free too. Isn’t the Internet wonderful?
With single-user OAuth in API 1.1, all visitors to your website will be sharing the rate limit
available to your Twitter app. The good thing is that rate limits for queries, such as user
timelines and search are increased to 720 requests per hour in API 1.1. This is certainly enough
for personal and small commercial websites. If your website gets more than 720 page views per
hour, you will have to code with multi-user OAuth to make Javascript work.
jQuery is a free Javascript library that dramatically simplifies the tasks of manipulating web
content and running Ajax communication with servers. There are other Javascript libraries you
can use in your Twitter API programming, but I find jQuery to be the fastest for performance
and the easiest to program. There is a wealth of free jQuery plugins, especially for user
interface programming.
You can download the latest copy of this library from http://jquery.com/download/. The source
code for this ebook contains a copy of the compressed version of jQuery in the form of
jquery.min.js.
Before we get started with actual Twitter programming, let’s go through a brief tutorial on the
jQuery techniques you’ll need most often, including Ajax requests from servers. This section
assumes that you are familiar with Javascript, but haven’t used jQuery before.
You must load the jQuery library in your HTML file before running any jQuery commands. It can
be loaded from your local server or a remote URL. There is a lot of controversy as to the best
location of this load command for performance, with some advocating that it be placed in the
<head> section before the page <body>, and others in favor of the end of the <body>. This
tutorial will put the jQuery at the start of the pages for simplicity. In later examples it will be
placed in the <head>. The one rule to follow is to put this statement before any other jQuery.
jQuery processing code begins with this line. It guarantees that the entire page has loaded and
all HTML elements were created before the jQuery code begins executing.
jQuery works with HTML elements, which can be a <span>, <div>, or any other element. You
tell jQuery to read from or write to elements by type, or by name. If you assign either an id or
class to an element, you can use that name to identify it. If an element has an id of test_span,
you identify it to jQuery with $('# test_span'). If it is a class, you use $('. test_span').
One of the coolest parts of jQuery is the way it lets you attach UI events to HTML elements, like
reacting to a click. This can be done with any elements, so you are no longer limited to form
elements, such as a button. The event creates an unnamed function that can run any other
Javascript or jQuery. The result is a highly responsive page.
The .html() function can be used to read or write any HTML element’s value. When .html() is
given a new value, it appears on the page immediately. In effect, you can write to any portion
of the page.
jquery_test.html
<script src="jquery.min.js"></script>
<script>
// Run once the page is loaded
jQuery(document).ready(function($) {
The resulting page displays Testing jQuery. If you click this text, it appears in an alert window.
When you close the window, the text changes to TESTING JQUERY. Admittedly a trivial
example, but pretty amazing in its simplicity and implied power.
With Twitter API 1.0 you could make an Ajax request directly to the Twitter server with a
technique called JSONP, which allowed you to communicate with a server from any domain.
Setting up JSONP on your own server is beyond the scope of this ebook, since it requires
additional security precautions. For the purposes of the sample code here, you should assume
that you can only call the server based scripts from a web page on the same domain. This
protects you from hacking attempts from computers outside your domain.
ajax_request.html
<script src='jquery.min.js'></script>
<script>
jQuery(document).ready(function($) {
// Make an Ajax request
$.ajax({
The combination of ajax_request.html and ajax_response.php is very basic, but it shows just
how easy Ajax can be with jQuery.
ajax_response.php
<?php
?>
Loading ajax_request.html in a web browser shows the server response a few seconds later.
A proxy server sounds technically complex, but all it really means is a server that sits between
the browser client and the final server that is the target of a request. In this case we need to
create a server script that can handle the OAuth portion of a Twitter API request. The complete
timeline_request.html
<script src='jquery.min.js'></script>
<script>
jQuery(document).ready(function($) {
// Make an Ajax request
$.ajax({
The server code in timeline_response.php called by the Ajax request uses the single-user
OAuth coding techniques described in my OAuth ebook. After getting the user timeline for the
@justinbieber account, it extracts the tweets, assembles them into a single string of HTML, and
prints the results. It also checks for the rate limit error code of 429, or any other error, and
prints an appropriate message. For simplicity it only prints the text of each tweet.
timeline_response.php
<?php
Loading the timeline_request.html page in a browser displays the latest tweets for this
account. Of course, in a real web page you would use CSS to combine this tweet stream with
the rest of the page in an attractive design. We’ll look at this type of CSS for tweets later in the
ebook.
Since this is an Ajax form, we don’t want to reload the page when the user clicks the Search
button, so we don’t actually create an HTML form. Instead we create the input field and button
elements, and then use jQuery to attach a click event to the button. When the user clicks the
button, the current value of the input field is read and passed to the search_response.php
script with Ajax. The result is a page that lets the user enter new search words, click Search, and
see the results repeatedly without the page reloading.
Because the Ajax request uses a URL to call the server, the search terms must be part of a valid
URL. A user can enter multiple search words separated by spaces in the input field, and spaces
are not valid in a URL. The search_request.html script uses the Javascript
encodeURIComponent() function to convert spaces into entities that are acceptable in a URL.
<script>
jQuery(document).ready(function($) {
Ajax Search:
<input name='search_terms' autofocus='autofocus'/>
<button id='search_button'>Search</button>
<div id='search_results'></div>
When search_response.php is called with Ajax, it extracts the value of the q argument that was
sent in the URL, and uses that to call the Twitter search API.
search_response.php
<?php
// Ignore retweets
if (isset($tweet['retweeted_status'])) {
continue;
}
} else {
print 'No search terms found';
}
?>
The result is a simple search page that uses Ajax to create a responsive user interface, and a
server to proxy the API request with Twitter. This is the foundation for any form based interface
that allows users to communicate with the Twitter API. It still needs CSS formatting, and we will
want to display a real tweet with all of its associated information. That comes next.
You now have the basic techniques you need to create a useful Twitter app with a Javascript
user interface. The next step is fleshing it out to look like an app and display tweets correctly.
Twitter has strict rules about displaying tweets on public web pages. Along with making this app
look good, you’ll also learn how to make it meet these display rules.
I’ve broken the app into separate files to make them easier to modify and reuse in your own
future code. Here is a listing of all the pieces:
search_client.html
search_client.css
search_client.js
tweet_template.html
tweet.css
display_lib.php
search_server.php
search_client.html
<head>
<title>Twitter Search</title>
<link href="search_client.css" type="text/css" rel="stylesheet" />
<link href="tweet.css" type="text/css" rel="stylesheet" />
<script src="jquery.min.js"></script>
<script src="search_client.js"></script>
</head>
<body>
<div id="search_box">
<h1>Twitter Search</h1>
<input name="search_terms" autofocus="autofocus"/>
<button id="search_button">Search</button>
</div>
<div id="search_results"></div>
</body>
CSS files
There are two CSS files used by this app: search_client.css and tweet.css. Documenting all the
CSS used to produce the app would take more space than I have in this ebook. Hopefully the
CSS is self-explanatory. Tweet.css is used to format an individual tweet. I split these in two so
search_client.css
body {
width:900px;
margin:24px auto;
}
p,ul,li,h1,h2 {
margin:0;
padding:0;
}
#search_box {
background:#f3f3f3;
padding:25px;
width:500px;
border:1px solid #bbb;
}
h1 {
font-size:24px;
margin-bottom:12px;
}
input[name=search_terms] {
font-size:23px;
padding:6px;
float:left;
margin-right:16px;
}
#search_button {
background-color:#019AD2;
-webkit-border-radius:9px;
border-radius:9px;
border:1px solid #057ED0;
color:#fff;
font-size:24px;
font-weight:700;
padding:6px 24px;
text-shadow:1px 1px 0 #333;
cursor:pointer;
}
.search_button:hover {
background-color:#378de5;
.search_button:active {
position:relative;
top:1px;
}
#search_results{
display: inline-block;
width:600px;
margin-top:12px;
}
search_client.js
// jQuery script for search request with server
jQuery(document).ready(function($) {
success: function(data){
// Display the results
$('#search_results').html(data);
}
})
})
});
tweet_template.html
<div class="tweet">
<div class="tweet_left">
<div class="tweet_image">
<a href="https://twitter.com/[screen_name]">
<img src="[profile_image_url]">
</a>
</div>
</div>
<div class="tweet_right">
<div class="tweet_triangle"></div>
<div class="tweet_row">
<div class="tweet_username">
<a href="https://twitter.com/[screen_name]" target="search">[screen_name]</a>
<span class="tweet_name">[name]</span>
</div>
</div>
<div class="tweet_row">
<div class="tweet_text">[tweet_text]</div>
</div>
<div class="tweet_row">
<div class="tweet_timestamp">
<img class="stream_bluebird" src="/oauth/images/bird_16_blue.png">
<span class="retweets">[retweet_count] retweets</span>
<a href="http://twitter.com/[screen_name]/status/[tweet_id]"
target="search" class="tweet_time_link">[created_at]</a>
<img src="reply.png" class="imageof_reply">
<a href="http://twitter.com/intent/tweet?in_reply_to=[tweet_id]"
target="search">Reply</a>
<img src="retweet.png" class="imageof_retweet">
<a href="http://twitter.com/intent/retweet?tweet_id=[tweet_id]"
target="search">Retweet</a>
<img src="favorite.png" class="imageof_favorite">
<a href="http://twitter.com/intent/favorite?tweet_id=[tweet_id]"
target="search">Favorite</a>
</div>
</div>
tweet.css
.tweet {
float:left;
padding-bottom:8px;
position:relative;
width:550px;
}
.tweet_left {
float:left;
width:28px;
margin:2px 4px 4px 2px;
}
.tweet_left img {
border:2px solid #fff;
margin-top:1px;
}
.tweet_left img:hover {
border:2px solid #C40001;
}
.tweet_right {
-moz-border-radius:6px;
-webkit-border-radius:6px;
border-radius:6px;
border:1px solid #DADADA;
float:right;
position:relative;
width:478px;
padding:2px 5px 4px;
}
.tweet_triangle {
background:url(twitter_triangle.gif) no-repeat scroll 100% 0 transparent;
height:13px;
.tweet_row {
line-height:15px;
position:relative;
}
.tweet_username {
color:#999;
font-size:14px;
margin-top:4px;
}
.tweet_username a {
color:#333;
font-size:16px;
margin-right:4px;
font-weight:700;
text-decoration:none;
}
.tweet_text {
font-size:14px;
color:#222;
line-height:20px;
word-wrap:break-word;
width:100%;
margin:0 0 3px;
padding:0;
}
.tweet_text a {
color:#5799DB;
text-decoration:none;
}
.tweet_timestamp,.tweet_timestamp a {
color:#999;
font-size:12px;
text-decoration:none;
float:left;
display:inline;
}
.tweet_timestamp {
.tweet_timestamp .retweets {
float:left;
margin-right:6px;
}
.tweet_timestamp img {
float:left;
margin-left:4px;
margin-right:3px;
margin-top:-2px;
}
.tweet_timestamp .stream_bluebird {
margin-left:0;
margin-right:4px;
}
.tweet_timestamp .imageof_reply {
margin-right:2px;
}
.tweet_timestamp .imageof_retweet {
margin-top:-1px;
}
a:hover {
text-decoration:underline;
}
display_lib.php
<?php
// Linkify URLs
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
// Linkify @mentions
$text = preg_replace("/\B@(\w+(?!\/))\b/i",
'<a href="https://twitter.com/\\1">@\\1</a>', $text);
// Linkify #hashtags
$text = preg_replace("/\B(?<![=\/])#([\w]+[a-z]+([0-9]+)?)/i",
'<a href="https://twitter.com/#!/search/%23\\1">#\\1</a>', $text);
return $text;
}
?>
} else {
print 'No search terms found';
}
?>
I’ve helped a lot people get started with Twitter API programming, and the problems they
experience fall into predictable patterns. Here are the most common errors and their solutions.
This error can be very frustrating, because nothing happens when you run the Ajax request. The
solution is to include an error parameter in your jQuery ajax() function. This can be as simple as
an alert box that warns you. It can be removed once your code is debugged and functioning.
Use Firebug
Once you get serious about jQuery programming, you should install Firebug in your browser. It
is invaluable for seeing all the HTML elements in a page and watching Ajax requests as they
happen.
http://books.140dev.com/ebook_js/code/search_response.php?q=Justin+bieber