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,433 responses to “Using the BitLy API to shorten urls”

  1. KevinBup Avatar
    KevinBup

    prednisone 5mg over the counter: prednisone 20 mg without prescription – 80 mg prednisone daily

  2. Inscreva-se na binance 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://www.binance.com/register?ref=IXBIAFVY

  3. KeithDep Avatar
    KeithDep

    https://ivermectinfast.shop/# ivermectin tablets online

  4. KevinBup Avatar
    KevinBup

    where to buy ivermectin: ivermectin treatment tablets – ivermectin price uk

  5. KevinBup Avatar
    KevinBup

    antibiotics online pharmacy usa: amoxil 500mg tablets usa – amoxil without prescription usa

  6. Allendwems Avatar
    Allendwems

    https://amoxilfast.shop/# order amoxicillin online no prescription

  7. KevinBup Avatar
    KevinBup

    trusted ivermectin pharmacy: Stromectol – trusted ivermectin pharmacy

  8. KeithDep Avatar
    KeithDep

    https://amoxilfast.shop/# fast delivery amoxicillin usa

  9. KevinBup Avatar
    KevinBup

    prednisone 20mg cheap: buy prednisone online usa – can you buy prednisone over the counter

  10. KevinBup Avatar
    KevinBup

    buy amoxil online usa: amoxil without prescription usa – amoxil fast

  11. KevinBup Avatar
    KevinBup

    trusted antibiotic pharmacy usa: amoxil without prescription usa – trusted antibiotic pharmacy usa

  12. KeithDep Avatar
    KeithDep

    https://ivermectinfast.shop/# buy stromectol online usa

  13. Rayfordpag Avatar
    Rayfordpag

    fast delivery amoxicillin usa: fast delivery amoxicillin usa – azithromycin amoxicillin

  14. Allendwems Avatar
    Allendwems

    http://stericarepharmacy.com/# prednisone 10mg cost

  15. KevinBup Avatar
    KevinBup

    generic amoxicillin online: buy amoxil online usa – amoxicillin capsules online

  16. Rayfordpag Avatar
    Rayfordpag

    buy prednisone 50 mg: prednisone tablets 10mg 20mg – buy prednisone canada

  17. KevinBup Avatar
    KevinBup

    where can i buy prednisone without prescription: prednisone 30 mg coupon – prednisone 2.5 mg cost

  18. Rayfordpag Avatar
    Rayfordpag

    amoxicillin capsules online: trusted antibiotic pharmacy usa – fast delivery amoxicillin usa

  19. KeithDep Avatar
    KeithDep

    https://stericarepharmacy.com/# prednisone cream brand name

  20. KevinBup Avatar
    KevinBup

    antiparasitic medication usa: ivermectin treatment tablets – ivermectin oral

  21. Allendwems Avatar
    Allendwems

    http://ivermectinfast.com/# ivermectin treatment tablets

  22. Rayfordpag Avatar
    Rayfordpag

    stromectol delivery united states: stromectol without prescription usa – stromectol without prescription usa

  23. BarryHus Avatar
    BarryHus

    prednisone 20mg online without prescription: prednisone – buy prednisone online uk

  24. KeithDep Avatar
    KeithDep

    https://stericarepharmacy.shop/# purchase prednisone no prescription

  25. KevinBup Avatar
    KevinBup

    prednisone uk price: prednisone for allergies and asthma – can i buy prednisone online without a prescription

  26. Rayfordpag Avatar
    Rayfordpag

    antiparasitic medication usa: stromectol delivery united states – ivermectin 5

  27. KeithDep Avatar
    KeithDep

    https://stericarepharmacy.com/# no prescription online prednisone

  28. KevinBup Avatar
    KevinBup

    trusted ivermectin pharmacy: Stromectol – buy stromectol pills

  29. Rayfordpag Avatar
    Rayfordpag

    stromectol 3mg cost: trusted ivermectin pharmacy – generic ivermectin online pharmacy

  30. Allendwems Avatar
    Allendwems

    https://amoxilfast.shop/# bacterial infection medication

  31. KeithDep Avatar
    KeithDep
  32. Michaelves Avatar
    Michaelves

    Paw Trust Meds: Paw Trust Meds – pet prescriptions online

  33. ArthurLap Avatar
    ArthurLap

    best canadian pharmacy online: NorthAccess Rx – canada rx pharmacy world

  34. AndrewHoozy Avatar
    AndrewHoozy

    canada online pharmacy: NorthAccess Rx – canadadrugpharmacy com

  35. Gabrielnes Avatar
    Gabrielnes

    http://globalindiapharmacy.com/# india pharmacy mail order

  36. WilliamSip Avatar
    WilliamSip

    https://globalindiapharmacy.shop/# Global India Pharmacy

  37. Michaelves Avatar
    Michaelves

    canadian drugstore online: canadian pharmacy online – canada online pharmacy

  38. AndrewHoozy Avatar
    AndrewHoozy

    best canadian online pharmacy: onlinecanadianpharmacy 24 – legitimate canadian pharmacy

  39. Gabrielnes Avatar
    Gabrielnes
  40. Michaelves Avatar
    Michaelves

    top 10 pharmacies in india: best online pharmacy india – Global India Pharmacy

  41. AndrewHoozy Avatar
    AndrewHoozy

    canadian pharmacies compare: NorthAccess Rx – canada ed drugs

  42. Gabrielnes Avatar
    Gabrielnes

    https://pawtrustmeds.shop/# pet meds for dogs

  43. WilliamSip Avatar
    WilliamSip

    https://globalindiapharmacy.com/# Global India Pharmacy

  44. Michaelves Avatar
    Michaelves

    vet pharmacy: pet meds for dogs – Paw Trust Meds

  45. ArthurLap Avatar
    ArthurLap

    dog medication online: Paw Trust Meds – Paw Trust Meds

  46. AndrewHoozy Avatar
    AndrewHoozy

    Global India Pharmacy: Global India Pharmacy – Global India Pharmacy

  47. Gabrielnes Avatar
    Gabrielnes

    https://globalindiapharmacy.shop/# Global India Pharmacy

  48. Michaelves Avatar
    Michaelves

    canadian pharmacy meds review: NorthAccess Rx – canadian pharmacy scam

  49. AndrewHoozy Avatar
    AndrewHoozy

    Paw Trust Meds: best pet rx – Paw Trust Meds

Leave a Reply

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