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:

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:

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.