Using the BitLy API to shorten urls

I was asked to place Twitter messages with product links when new products were added to a webshop. I’ve used my own Twitter class for posting the first test Tweet then I went looking for a shorten url a service to shorten the product links.

There are many url shorten services available on the internet, one of these services is Bitly.
The reasons why I’ve chosen Bitly:
– Urls don’t expire after a period of time.
– Bitly provides a click url summary (although Google Analytics can be used for this instead)
– Urls are short in length so i could use the remaining Tweet length for a small product description.
– And more important, they provide an easy to use API.
– Authentication does not require a password, we can use our API key instead.

Before we can connect to the API, we need a Bitly account, the account can be created at http://bit.ly/ to obtain a free API key.

The communication process is quite simple:
– Authenticate with your Bitly username and API key
– Call the right Bitly API url with the correct parameters for the action we want to perform
– Process the result

Below are some snippets of my Bitly class:

class BitLy
{
	/**
	 * Version of the bit ly api
	 * @var string
	 */
	private $sApiVersion = '2.0.1';

	/**
	 * Url of the api
	 * @var string
	 */
	private $sApiUrl = 'http://api.bit.ly/';

	/**
	 * username
	 * @var string
	 */
	private $sUsername;

	/**
	 * apikey
	 * @var string
	 */
	private $sApiKey;

	/**
	 * Set username and apikey
	 *
	 * @param string $sUsername
	 * @param string $sApiKey
	 * @return void
	 */
	public function  __construct($sUsername, $sApiKey) {
		$this->setUsername($sUsername);
		$this->setApiKey($sApiKey);
	}

	...

	/**
	 * shorten
	 *
	 * @param string $sLongUrl
	 * @return object with shortend url and hash
	 */
	public function shorten($sLongUrl)
	{
		return $this->process('shorten', urlencode($sLongUrl));
	}

	/**
	 * expand
	 *
	 * @param string $sShortUrl
	 * @return object with original url
	 */
	public function expand($sShortUrl)
	{
		return $this->process('expand', urlencode($sShortUrl));
	}

	...

	/**
	 * process, checks the action and returns the result
	 *
	 * @param string $sAction
	 * @param string $sParam
	 */
	private function process($sAction, $sUrlToParse)
	{
		// Check the url, if no http is present, add it
		if(strstr($sUrlToParse, 'http://') === false) {
			$sUrlToParse = 'http://'.$sUrlToParse;
		}

		// Compose action url
		$sParam = ($sAction == 'shorten') ? 'longUrl='.$sUrlToParse : 'shortUrl='.$sUrlToParse;
		$sActionUrl = $this->sApiUrl.$sAction.'?version='.$this->sApiVersion.'&'.$sParam.'&login='.$this->sUsername.'&apiKey='.$this->sApiKey.'&format=xml';

		// Get data
		libxml_use_internal_errors(true);
		$oData = simplexml_load_file($sActionUrl);
		if(!$oData) {
			throw new Exception('Api returned an invalid response!');
		}

		// Check for errors
		if($oData->statusCode == 'ERROR') {
			throw new Exception($oData->errorCode.': '.$oData->errorMessage);
		}

		// Build result object
		$oResult				= new stdClass();
		$oResult->requestedUrl	= $sUrlToParse;
		$oResult->resultUrl	= (string)$oData->results->nodeKeyVal->shortUrl;
		$oResult->hash		= (string)$oData->results->nodeKeyVal->hash;

		return $oResult;
	}

The reason why I build a result object is because of the fact that the server where the class is deployed doesn’t support JSON but JSON is also available as return format.

Furthermore, generated urls can be saved to our Bitly account history by adding an additional parameter to the url (history = 1). Another nice option of the API is to shorten the URL to a keyword, this can be achieved by sending the (keyword=your keyword) parameter along.

The complete API manual can be found at Google Code which also describes how to get click statistics of the shortened links.

Comments

3,317 responses to “Using the BitLy API to shorten urls”

  1. 1.95.120.11 Avatar

    References:

    Buy legal steroids bodybuilding

    References:
    http://120.211.66.170:8418/stuartmusselma

  2. blv-rd.tech Avatar

    References:

    Body beast supplements alternatives

    References:
    http://www.annunciogratis.net/author/helenloehr

  3. 111.230.98.74 Avatar

    References:

    Steroid trenbolone acetate

    References:
    http://naughtycat.biz:3333/annelieses2252

  4. heyvende.com Avatar

    References:

    Steroids bad for you

    References:
    https://www.garagesale.es/author/lindsaygars/

  5. http://122.116.190.233/ Avatar

    References:

    Winstrol steroid before and after

    References:
    http://1.95.7.169:3000/dawndunne71454

  6. mahavet.org Avatar

    References:

    Everything you need to know about steroids

    References:
    http://154.39.79.147:3000/alfred41548734

  7. KevinBup Avatar
    KevinBup

    purchase prednisone from india: buy prednisone online usa – prednisone 30 mg daily

  8. 10xhire.io Avatar

    References:

    Legal steroid supplements

    References:
    http://git.qniao.cn/austinpak1548

  9. Rayfordpag Avatar
    Rayfordpag

    amoxicillin 500 mg online: amoxil – bacterial infection medication

  10. http://219.157.255.213/ Avatar

    References:

    The use of anabolic steroids during adolescence can cause

    References:
    https://git.init.cool/sonfrance23255

  11. 121.43.186.169 Avatar

    References:

    Deca cycle for beginners

    References:
    https://testgitea.educoder.net/phyllisbatista

  12. KevinBup Avatar
    KevinBup

    ivermectin oral tablets usa: ivermectin tablets online – ivermectin fast

  13. Rayfordpag Avatar
    Rayfordpag

    buy amoxil online usa: safe antibiotics online source – amoxil fast

  14. git.scinalytics.com Avatar

    References:

    Anabolic steroid classification

    References:
    http://47.115.132.164:5500/jefferyblackwe

  15. git.meshel.cn Avatar

    References:

    Superdrol 250 reviews

    References:
    http://43.143.209.246:6300/leonidaanr643

  16. www.bongmedia.tv Avatar

    References:

    Did the rock take steroids

    References:
    https://www.propose.lk/@margomorehead5

  17. KeithDep Avatar
    KeithDep
  18. KevinBup Avatar
    KevinBup

    buy amoxil online usa: fast delivery amoxicillin usa – amoxil fast

  19. git.nathanspackman.com Avatar

    References:

    Effects of anabolic steroids on the body

    References:
    http://120.26.116.243:3000/raulwashington

  20. globalhospitalitycareer.com Avatar

    References:

    Anabolic steroids are which of the following

    References:
    https://nonstopvn.net/@spencerashkana?page=about

  21. Allendwems Avatar
    Allendwems

    http://ivermectinfast.com/# stromectol without prescription usa

  22. Rayfordpag Avatar
    Rayfordpag

    Stromectol: ivermectin tablets online – stromectol how much it cost

  23. www.binance.info注册 Avatar

    Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me? https://accounts.binance.com/lv/register?ref=SMUBFN5I

  24. KevinBup Avatar
    KevinBup

    bacterial infection medication: bacterial infection medication – amoxil without prescription usa

  25. KeithDep Avatar
    KeithDep

    http://ivermectinfast.com/# ivermectin buy nz

  26. Rayfordpag Avatar
    Rayfordpag

    ivermectin treatment tablets: stromectol delivery united states – generic ivermectin online pharmacy

  27. KevinBup Avatar
    KevinBup

    prednisone 20 mg tablet price: prednisone for inflammation treatment – prednisone cream rx

  28. Rayfordpag Avatar
    Rayfordpag

    Stromectol: buy stromectol online usa – ivermectin fast

  29. KevinBup Avatar
    KevinBup

    can you buy prednisone online uk: buy prednisone online usa – buy prednisone with paypal canada

  30. Allendwems Avatar
    Allendwems

    https://amoxilfast.com/# where to get amoxicillin over the counter

Leave a Reply

Your email address will not be published. Required fields are marked *