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

1,561 responses to “Using the BitLy API to shorten urls”

  1. Conradnet Avatar
    Conradnet

    Nausea Care US: zofran generic – Nausea Care US

  2. historydb.date Avatar

    References:

    Turning stone casino

    References:
    https://md.swk-web.com/s/oZLPPAjg4

  3. JeffreyFiseE Avatar
    JeffreyFiseE
  4. Conradnet Avatar
    Conradnet

    otc muscle relaxer: Spasm Relief Protocols – muscle relaxer medication

  5. DavidMib Avatar
    DavidMib

    ondansetron medication zofran generic zofran side effects

  6. JeffreyFiseE Avatar
    JeffreyFiseE

    http://gastrohealthmonitor.com/# prilosec side effects

  7. JeffreyFiseE Avatar
    JeffreyFiseE

    http://spasmreliefprotocols.com/# muscle relaxer medication

  8. Conradnet Avatar
    Conradnet

    zofran dosage: Nausea Care US – Nausea Care US

  9. JeffreyFiseE Avatar
    JeffreyFiseE

    https://spasmreliefprotocols.shop/# muscle relaxer medication

  10. Conradnet Avatar
    Conradnet

    methocarbamol dosing: Spasm Relief Protocols – buy tizanidine without prescription

  11. DavidMib Avatar
    DavidMib

    antispasmodic medication zanaflex medication zanaflex medication

  12. Conradnet Avatar
    Conradnet

    Gastro Health Monitor: prilosec omeprazole – omeprazole medication

  13. JeffreyFiseE Avatar
    JeffreyFiseE

    https://gastrohealthmonitor.com/# Gastro Health Monitor

  14. https://googlino.com/ Avatar

    References:

    Steroids that start with p

    References:
    https://googlino.com/

  15. Conradnet Avatar
    Conradnet

    Nausea Care US: Nausea Care US – Nausea Care US

  16. JeffreyFiseE Avatar
    JeffreyFiseE
  17. pad.stuve.uni-ulm.de Avatar

    References:

    Female anabolic steroids

    References:
    pad.stuve.uni-ulm.de

  18. WilliamNex Avatar
    WilliamNex

    india pharmacy mail order: mail order pharmacy india – online pharmacy india

  19. VaughnOvaph Avatar
    VaughnOvaph
  20. MatthewCoing Avatar
    MatthewCoing

    over the counter muscle relaxers that work: muscle relaxer tizanidine – tizanidine hydrochloride

  21. WilliamNex Avatar
    WilliamNex

    reputable indian pharmacies: indian pharmacies safe – india pharmacy mail order

  22. StephenPep Avatar
    StephenPep

    online shopping pharmacy india Indo-Generic Export indian pharmacy online

  23. VaughnOvaph Avatar
    VaughnOvaph

    https://indogenericexport.shop/# online pharmacy india

  24. WilliamNex Avatar
    WilliamNex

    india online pharmacy: п»їlegitimate online pharmacies india – india pharmacy mail order

  25. VaughnOvaph Avatar
    VaughnOvaph
  26. RandyLew Avatar
    RandyLew

    https://bajameddirect.com/# farmacia mexicana en linea

  27. WilliamNex Avatar
    WilliamNex

    US Meds Outlet: US Meds Outlet – canadian pharmacy cheap

  28. StephenPep Avatar
    StephenPep

    US Meds Outlet online pharmacy dubai compare pharmacy prices

  29. RandyLew Avatar
    RandyLew

    https://indogenericexport.com/# buy tizanidine without prescription

  30. WilliamNex Avatar
    WilliamNex

    mexican online pharmacy wegovy: order from mexico – BajaMed Direct

  31. WilliamNex Avatar
    WilliamNex

    india pharmacy: cheapest online pharmacy india – top 10 pharmacies in india

  32. RandyLew Avatar
    RandyLew

    http://indogenericexport.com/# buy methocarbamol without prescription

  33. WilliamNex Avatar
    WilliamNex

    canada discount pharmacy: US Meds Outlet – online pharmacy delivery dubai

  34. HarryZoowl Avatar
    HarryZoowl

    reputable indian pharmacies: indianpharmacy com – reputable indian online pharmacy

  35. RandyLew Avatar
    RandyLew

    http://usmedsoutlet.com/# canadian pharmacy meds reviews

  36. WilliamNex Avatar
    WilliamNex

    US Meds Outlet: trusted online pharmacy reviews – US Meds Outlet

  37. StephenPep Avatar
    StephenPep

    purple pharmacy online ordering pharmacy mexico city mexican pharmacies that ship

  38. RandyLew Avatar
    RandyLew

    https://indogenericexport.shop/# muscle relaxant drugs

  39. HarryZoowl Avatar
    HarryZoowl

    BajaMed Direct: pharmacy in mexico – BajaMed Direct

  40. WilliamNex Avatar
    WilliamNex

    п»їmexican pharmacy: mexico online farmacia – order antibiotics from mexico

  41. medibang.com Avatar

    References:

    Melbourne crown casino

    References:
    medibang.com

  42. RandyLew Avatar
    RandyLew

    http://indogenericexport.com/# robaxin medication

Leave a Reply

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