Recently while working on adding the feature to enter your own bit.ly API key to my Easy Retweet WordPress Plugin, I found out that by default all short urls created using bit.ly API (both REST and JavaScript API’s) are not associated with your account.
Upon further researching I found that there is an undocumented way of associating the urls created with your account. The undocumented way is to add an additional parameter called history
with value 1 to the API URL.
Using the history parameter in bit.ly’s REST API
So for REST API, you have to use the following url.
http://api.bit.ly/shorten?version=2.0.1&longUrl=http://sudarmuthu.com&login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&format=json&history=1
If you are using PHP, then code would be
function get_bitly_shorturl($longurl) {
$url = "http://api.bit.ly/shorten?version=2.0.1&login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&format=json&history=1" . "&longurl=$longurl";
//using curl
$curlObject = curl_init();
curl_setopt($curlObject,CURLOPT_URL,$url);
curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curlObject,CURLOPT_HEADER,false);
$result_json = curl_exec($curlObject);
curl_close($curlObject);
//decode JSON. Assumes that it is PHP5
$result = json_decode($result_json);
return $result['results'][shortUrl];
}
If you are going to use it in WordPress, then you can use the inbuilt WP_Http class instead of curl as suggested by Ozh. The following code shows you how it can be done in WordPress
function get_bitly_shorturl($longurl) {
$url = "http://api.bit.ly/shorten?version=2.0.1&login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&format=json&history=1" . "&longurl=$longurl";
//using WP_Http present in WordPress
$request = new WP_Http;
$result_json = $request->request($url);
$result = json_decode($result_json);
return $result['results'][shortUrl];
}
Using the history parameter in bit.ly’s JavaScript API
If you are using bit.ly’s JavaScript API, then it is not as straight forward as the REST API. Instead of using the provided shorten method, you have to use the low level call method.
The following code shows you how you can do it in JavaScript API.
BitlyClient.call('shorten', {'longUrl':'http://sudarmuthu.com', 'history':'1'}, 'BitlyCB.shortenResponse');
I am not sure why bit.ly is not associating the created shorturls automatically with your account, when you provide the API Key, it is the expected default behavior. Or at least they could have documented about this history variable in their API. I guess only someone from bit.ly can answer this. 🙂