Shortening Links with Google

A recent project necessitated the use of a link shortener, which I had never used before, so I first turned to http:://goo.gl to see what was involved. I was pleasantly surprised with the ease of integrating Google’s API into my code. The following screenshots detail this simple process.

1. Get your API key from your Google API console

Get your API key
Get Your API Key

2. Turn on the link shortening service via the console

Turn on the service
Turn On the Service

3. Make a call to the service from your code

function shortenUrl( $sLongUrl ) {
	$ch = curl_init( 'https://www.googleapis.com/urlshortener/v1/url?key=' . _GOOGLE_API_KEY );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_POST, true );
	curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Content-type: application/json' ) );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( array( 'longUrl' => $sLongUrl ) ) );

	$result = curl_exec( $ch );
	curl_close( $ch );

	return $result;
}

All we are doing here is using PHP’s curl to make a post to the Google API by passing a JSON-encoded array, loaded with our long URL.

4. Handle the result

        .
        .
        .
	success: function( response ) {

		if ( response[ 'error' ] ) {

			shortUrl = '';

		}
		else {

		        shortUrl = response[ 'id' ];

                }

	},
	failure: function( response ) {

		shortUrl = '';

	}

} );

I am making an AJAX call from jQuery here, but the important part is that the response comes back as an array. If the “error” index is set, there was a problem. Otherwise, your shortened URL will be contained in the “id” index.

And that’s all there is to it!