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

4,162 responses to “Using the BitLy API to shorten urls”

  1. architecturewiki.site Avatar

    References:

    Bedste online slots med høj RTP

    References:
    https://uichin.net/ui/home.php?mod=space&uid=2671677

  2. jobsathealthcare.com Avatar

    References:

    Populære casinoer med høj udbetaling

    References:
    http://git.modelhub.org.cn:980/pearlinemackay

  3. philosophywiki.space Avatar

    References:

    Online casino udbetaling og sikkerhed

    References:
    http://kuniunet.com/home.php?mod=space&uid=3061115

  4. git.lucas-michel.fr Avatar

    References:

    Online casino dansk tilladelse høj udbetaling

    References:
    https://git.mana-web.com/ethelcuni7449

  5. "oppna ett binance-konto Avatar

    I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  6. srsbkn.eu.org Avatar

    References:

    Casinoer med god udbetalingshistorik

    References:
    http://hcrw.co.kr/hcrw/bbs/board.php?bo_table=er_board&wr_id=109079

  7. RobertBag Avatar
    RobertBag

    https://vetpharmfirst.com/# dog prescriptions online

  8. pad.stuve.de Avatar

    References:

    Bedste udbetaling på danske casinoer

    References:
    https://jszst.com.cn/home.php?mod=space&uid=6882547

  9. http://warblog.hys.cz/ Avatar

    References:

    Casinoer med bedst udbetaling på bordspil

    References:
    https://www.9tj.net/home.php?mod=space&uid=542798

  10. gojourney.xsrv.jp Avatar

    References:

    Udbetaling af store gevinster casino

    References:
    http://www.qianqi.cloud/home.php?mod=space&uid=1286171

  11. https://git.lhqs.ink/ Avatar

    References:

    Høj udbetaling på mobil casino

    References:
    https://platform.giftedsoulsent.com/chastitybeaudo

  12. https://sonnik.nalench.com/ Avatar

    References:

    Hvilke spil udbetaler bedst

    References:
    https://hack.allmende.io/s/LVMAzCBqI

  13. Kevincoini Avatar
    Kevincoini

    worldwide pharmacy: safe online pharmacies – no script pharmacy

  14. all.caeta.mx Avatar

    References:

    Casinoer med høj udbetaling og lave gebyrer

    References:
    https://em-drh.com/employer/casinos-mit-hohem-rtp-2026-beste-auszahlungsquote/

  15. lpris-iua.nu Avatar

    References:

    Maksimer dine gevinster på casino

    References:
    http://demo.sunflowermachinery.com/henryzink96271

  16. Michaelpak Avatar
    Michaelpak

    online pharmacy without scripts Online Pharm First online pharmacy no prescription

  17. mensvault.men Avatar

    References:

    Gennemsigtige casino udbetalingsrater

    References:
    https://lichnyj-kabinet-vhod.ru/user/gaswrench08/

  18. cruzenews.com Avatar

    References:

    Test af casino udbetalinger

    References:
    http://bbs.pcgpcg.net/home.php?mod=space&uid=1062042

  19. git.refinementservices.com Avatar

    References:

    Høj udbetaling på mobil casino

    References:
    https://www.peter-bartke.de/danellebreeze

  20. swimmingwiki.site Avatar

    References:

    Udbetalingsmuligheder

    References:
    https://hack.allmende.io/s/GMOuXFSEZy

  21. gitea.shirom.me Avatar

    References:

    Casinoer med højeste udbetalingsprocent

    References:
    https://career.ltu.bg/employer/casinos-mit-schneller-auszahlung-2026-im-test/

  22. www.shkxrd.com Avatar

    References:

    Bedste casino udbetalinger i Skandinavien

    References:
    https://phoebe.roshka.com/gitlab/kristianbracke

  23. actsolution.iptime.org Avatar

    References:

    Højeste gevinstmuligheder online casino

    References:
    https://git.nathanspackman.com/ahmadnavarro3

  24. vcs.cozydsp.space Avatar

    References:

    Casinoer med flest jackpot udbetalinger

    References:
    https://gitea.cantrell.io/sherlyncode767

  25. academicbard.com Avatar

    References:

    RTP og udbetalinger på online casino

    References:
    https://git.danpeak.co.uk/adamcrompton99

  26. LanceUnure Avatar
    LanceUnure

    online vet pharmacy Vet Pharm First online pet pharmacy

  27. http://www.jcdqzdh.com/ Avatar

    References:

    Udbetalingsmetoder

    References:
    http://karayaz.ru/user/attacknail86/

  28. https://tunelifystream.com/adand008813249 Avatar

    References:

    Casino med fokus på spillerens udbetaling

    References:
    https://hadln.net:9443/johnieriddle1

Leave a Reply

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