Using the Bit.ly and Twitter API

Bit.lyI did a little experiment and created a tweet bot that would announce every article I just finished reading. There were two problems with this – 1) I was putting out two much noise in my twit stream, 2) I may not necessarily want everyone to know when I’m reading and not working, heh. So I canned the idea.

Poking around these APIs (Twitter and Bit.ly) really opened my eyes quite a bit as to how powerful these simple services can be once the internals are exposed. Bit.ly ran an API contest and some of the entrant applications will blow your mind. A simple URL shortener can produce so much power. I wish I would have know about the contest a little earlier.

What I’m going to show here is almost the same as the 140it.com application, but my version is much more simplified. I also want to test a syntax highlighting plugin for PHP and many other languages which uses GeSHi.

So, I’ll just jump to the code and not go into the application logic. Here is the first part to shorten a URL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// get shortUrl
$ch = curl_init();
$url = 'http://api.bit.ly/shorten';
$post_string = 'longUrl='.urlencode($data['url']).'&version=2.0.1';
$options = array(
    CURLOPT_URL => $url,
    CURLOPT_USERPWD => '[username]:[password]',
    CURLOPT_POSTFIELDS => $post_string,
    CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
curl_close($ch);
 
$response = json_decode($response);
if($response->statusCode!='OK') {
    return false;
}
$shortUrl = $response->results->$data['url']->shortUrl;
if(trim($shortUrl)=='') {
    return false;
}

And the next part to tweet about it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// tweet that
$ch = curl_init();
$url = 'http://twitter.com/statuses/update.json';
$post_string = 'status='.urlencode('Just Read: '.$data['name'].' - '.$shortUrl);
$options = array(
    CURLOPT_URL => $url,
    CURLOPT_USERPWD => '[username]:[password]',
    CURLOPT_POSTFIELDS => $post_string,
    CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
curl_close($ch);
 
$response = json_decode($response);
if(isset($response->error)) {
    return false;
}

If you decide to use this code, make sure your tweet is below the character limit. The above code does not reflect that.

One last thing, the real-time link stats at Bit.ly are the bomb. These guys are really pushing the boundaries here and I’m a huge fan. To access the real time stats, take an example URL like http://bit.ly/mQcHJ and add “info/” in the middle – http://bit.ly/info/mQcHJ.

Another last thing, the GeSHi plugin is also pretty cool. When copying the code, you don’t end up copying the line numbers.

image: bit.ly

Hey, like this post? Why not share it with a buddy?

Leave a Comment