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

  1. 47.117.245.9 Avatar

    References:

    What are steroids for bodybuilding

    References:
    https://twoheartsagency.com/@elmohuskey306

  2. parnian.app Avatar

    References:

    Steroids are a type of

    References:
    https://hellomusic.app/traceyopitz932

  3. git.kooera.com Avatar

    References:

    Best anabolic supplements for quick gains

    References:
    https://clipbeans.com/@isidroschlapp3?page=about

  4. git.mana-web.com Avatar

    References:

    About steroid

    References:
    https://shirme.com/ethanfoley2614

  5. findinall.com Avatar

    References:

    Steroids before and after reddit

    References:
    https://git.automathon.org/tandymccrae73

  6. http://106.52.21.251/ Avatar

    References:

    Best cycle for lean gains

    References:
    https://megastream.pl/@ltumammie4229?page=about

  7. https://vidspaceaiapp.com Avatar

    References:

    Pro bodybuilders steroid cycles

    References:
    https://git.thoughtvectors.uk/felipeh460700

  8. 47.103.48.2 Avatar

    References:

    Best stack for cutting fat and gaining muscle

    References:
    https://git.minecraftlegacy.com/ijjkendall0674

  9. http://47.103.100.52 Avatar

    References:

    Different ways to take steroids

    References:
    https://gitlab.rails365.net/hiltoncrick57

  10. git.hanumanit.co.th Avatar

    References:

    Decca steroids side effects

    References:
    https://gitea.personalsoftware.space/efrainboldt44

  11. DanielSpere Avatar
    DanielSpere

    best value pharmacy: verified india drug manufacturers – canadian online pharmacy reviews

  12. https://git.archieri.fr/ Avatar

    References:

    Is testosterone a steroid

    References:
    http://git.zxkedu.com:33769/desmond7581329

  13. 47.109.30.152 Avatar

    References:

    Hardening agent bodybuilding

    References:
    https://git.chalypeng.xyz/stuartwilliam3

  14. robots.rip Avatar

    References:

    Steroids effect on the body

    References:
    https://git.fs.cs.uni-frankfurt.de/aracelisspr750

  15. gitea.zachl.tech Avatar

    References:

    Why do anabolic steroids cause gynecomastia

    References:
    https://www.superphage.org/nikimacy485118

  16. Jeffreybrump Avatar
    Jeffreybrump

    mexico border medications usa access: mexipharmacy reviews – affordable border pharmacy mexico

  17. 123.60.146.54 Avatar

    References:

    Best muscle building supplement reviews

    References:
    https://kition.mhl.tuc.gr/sonyalazar6612

  18. tears.pt Avatar

    References:

    Weight lifting supplement stacks

    References:
    http://119.91.35.154:3000/sylviabaile510

  19. videyme.online Avatar

    References:

    Best supplements for bodybuilding without side effects

    References:
    https://smartastream.com/@bufordsabella?page=about

  20. flirta.online Avatar

    References:

    Steroids abuse side effects

    References:
    https://git.meshel.cn/bettyfrasier73

  21. JamesFaw Avatar
    JamesFaw

    https://trustedindiacarerx.com/# canada drugs online review

  22. Antonioesova Avatar
    Antonioesova

    reliable rx pharmacy trusted indian pharmacy usa rate online pharmacies

  23. DanielSpere Avatar
    DanielSpere

    canadian medication delivery to usa: canadian pharmacy reviews – CertifiedMaple RX

  24. Jeffreybrump Avatar
    Jeffreybrump

    express scripts pharmacy: verified india drug manufacturers – us online pharmacy

  25. JamesFaw Avatar
    JamesFaw

    http://bordervaluerx.com/# can i order online from a mexican pharmacy

  26. DanielSpere Avatar
    DanielSpere

    northern pharmacy: trusted indian pharmacy usa – indianpharmacy com

  27. JamesJep Avatar
    JamesJep

    https://trustedindiacarerx.com/# humana online pharmacy

  28. Jeffreybrump Avatar
    Jeffreybrump

    online pharmacy delivery: TrustedIndiaCare RX – thecanadianpharmacy

  29. JamesFaw Avatar
    JamesFaw
  30. DanielSpere Avatar
    DanielSpere

    CertifiedMaple RX: CertifiedMaple RX – canadian medication delivery to usa

  31. Jeffreybrump Avatar
    Jeffreybrump

    american pharmacy: india medication delivery to usa – best canadian pharmacy online

Leave a Reply

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