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

  1. Stephenunoge Avatar
    Stephenunoge

    Greetings! I found this site if you need pills at a discount. Pharmiexpress offers reliable delivery on health products. If you want to save, check it out: best pharmacy online. Thanks.

  2. AnthonyGoogy Avatar
    AnthonyGoogy

    Just now, I was looking for Amoxicillin for an infection and found Amoxicillin Express. It offers generic Amoxil cheaply. For fast relief, highly recommended: visit website. Cheers.

  3. Raymondcluse Avatar
    Raymondcluse

    Hey all! Just wanted to share a great site for those who need prescriptions fast. Pharmiexpress provides the best prices on health products. If you want to save, check it out: check availability. Best regards.

  4. Raymondcluse Avatar
    Raymondcluse

    Hello! I discovered a great site if you need generics at a discount. The site has express shipping on Rx drugs. If you want to save, visit here: pharmiexpress.com. Cheers.

  5. binance Avatar

    Your point of view caught my eye and was very interesting. Thanks. I have a question for you. https://www.binance.info/ph/register?ref=IU36GZC4

  6. Stephenunoge Avatar
    Stephenunoge

    Lately, I wanted to buy Ivermectin medication and stumbled upon this reliable site. They sell genuine Ivermectin delivered fast. For treating scabies quickly, this is the best place: source: ivermectinexpress.com. Cheers

  7. Raymondcluse Avatar
    Raymondcluse

    Actually, I was looking for antibiotics for a tooth infection and found this reliable site. They provide effective treatment cheaply. For fast relief, this is the best place: http://www.amoxicillinexpress.com. Best prices.

  8. Raymondcluse Avatar
    Raymondcluse

    Lately, I needed antibiotics for an infection and stumbled upon a great pharmacy. It offers Amoxicillin 500mg cheaply. If you need meds, highly recommended: AmoxicillinExpress Store. Cheers.

  9. Raymondcluse Avatar
    Raymondcluse

    Hey there! Just wanted to share a useful resource to order prescriptions fast. This store offers the best prices on all meds. If you want to save, highly recommended: express pharmacy. Thanks.

  10. Stephenunoge Avatar
    Stephenunoge

    Just now, I had to find Ivermectin for humans and stumbled upon this source. You can get genuine Ivermectin no script needed. If you need to treat lice effectively, check this out: Ivermectin Express. Best prices

  11. Raymondcluse Avatar
    Raymondcluse

    Just now, I was looking for Stromectol pills and came across this source. You can get genuine Ivermectin without a prescription. For treating infections effectively, check this out: https://ivermectinexpress.xyz/#. Hope it helps

  12. 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://accounts.binance.com/sl/register?ref=I3OM7SCZ

  13. Raymondcluse Avatar
    Raymondcluse

    Just now, I had to buy medication for a tooth infection and came across this source. They provide antibiotics without prescription fast. For fast relief, this is the best place: AmoxicillinExpress Store. Get well soon.

  14. 注册获取100 USDT Avatar

    Thanks for sharing. I read many of your blog posts, cool, your blog is very good.

  15. Stephenunoge Avatar
    Stephenunoge

    Just now, I was looking for antibiotics urgently and discovered this reliable site. They provide effective treatment with express shipping. For fast relief, check this out: https://amoxicillinexpress.com/#. Hope it helps.

  16. Raymondcluse Avatar
    Raymondcluse

    Greetings! Check out this resource to order prescriptions fast. The site provides reliable delivery on all meds. If you want to save, highly recommended: best pharmacy online. Thanks.

  17. Raymondcluse Avatar
    Raymondcluse

    Lately, I was looking for Ivermectin medication and found Ivermectin Express. They sell generic Stromectol with express shipping. For treating parasites quickly, highly recommended: http://ivermectinexpress.com/#. Fast delivery

  18. Raymondcluse Avatar
    Raymondcluse

    To be honest, I wanted to buy anti-parasitic meds pills and stumbled upon this source. They provide human grade meds without a prescription. If you need to treat scabies safely, this is the best place: http://www.ivermectinexpress.com. Cheers

  19. Stephenunoge Avatar
    Stephenunoge

    Recently, I was looking for Amoxicillin for an infection and discovered Amoxicillin Express. They sell generic Amoxil overnight. If you are in pain, this is the best place: http://www.amoxicillinexpress.com. Best prices.

  20. Stephenunoge Avatar
    Stephenunoge

    Hey all! I discovered a useful resource to order prescriptions at a discount. Pharmiexpress offers express shipping on all meds. For fast service, visit here: buy meds online. Thanks.

Leave a Reply

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