How to use the Google Shortener API

The Google url shortener allows you to take a long url and convert it into a shorter one. This is really useful when you have a url with a really long query string that you need to send to someone, or when you have a character restriction, for example when using Twitter. Google also provide an API for their shortener so that you can integrate this with your web applications, this post takes a look at how you can implement this.

Setup your application

To start with you need to register your application with Google and obtain an API key. To do this follow these steps:

Google API shortener code example

Now onto the code, this snippet will make a cURL request using the API key you just obtained:

    public function shortenUrl($longUrl)
    {
        $apiKey = 'yourapikey';

        $data = array('longUrl' => $longUrl, 'key' => $apiKey);
        $post = json_encode($data);

        $curl = curl_init();

        curl_setopt_array($curl,
            array(CURLOPT_URL => 'https://www.googleapis.com/urlshortener/v1/url',
                    CURLOPT_RETURNTRANSFER, 1,
                    CURLOPT_SSL_VERIFYPEER, 0,
                    CURLOPT_HEADER, 0,
                    CURLOPT_HTTPHEADER, array('Content-type:application/json')),
                    CURLOPT_POST, 1
                    CURLOPT_POSTFIELDS, $post));

        $response = curl_exec($curl);
        $json = json_decode($response);
        curl_close($curl);

        return $json->id;
    }

You can now call this function like so:

$shortUrl = shortenUrl('http://www.codesynthesis.co.uk');

Sign Up
comments powered by Disqus
Sign Up

Popular Tags

350x250

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.