Google URL Shortener API example

Google Provides URL Shortener API for free with a daily limit of 1,000,000 requests. For more API access you need to enable to Billing.

In order to access Google API you need to get API Key. URL Shortener API is available in JavaScript, Java, Python, Ruby, PHP, .NET and Objective-C.

Before going to the tutorial check the working example:
Google URL Shortener API Demo Download Google URL Shortener API
Working URL Shortener website:http://www.urlshortener.me

Below is the example of Google URL Shortener API with JavaScript.

<html>
<head>
</head>
<script type="text/javascript">
function makeShort() 
{
   var longUrl=document.getElementById("longurl").value;
    var request = gapi.client.urlshortener.url.insert({
	  'resource': {
      'longUrl': longUrl
	}
    });
    request.execute(function(response) 
	{

		if(response.id != null)
		{
			str ="<b>Long URL:</b>"+longUrl+"<br>";
			str +="<b>Short URL:</b> <a href='"+response.id+"'>"+response.id+"</a><br>";
			document.getElementById("output").innerHTML = str;
		}
		else
		{
			alert("error: creating short url n"+ response.error);
		}

    });
 }

function getShortInfo()
{
var shortUrl=document.getElementById("shorturl").value;

    var request = gapi.client.urlshortener.url.get({
      'shortUrl': shortUrl,
	'projection':'FULL'
    });
    request.execute(function(response) 
	{

		if(response.longUrl!= null)
		{
			str ="<b>Long URL:</b>"+response.longUrl+"<br>";
			str +="<b>Create On:</b>"+response.created+"<br>";
			str +="<b>Short URL Clicks:</b>"+response.analytics.allTime.shortUrlClicks+"<br>";
			str +="<b>Long URL Clicks:</b>"+response.analytics.allTime.longUrlClicks+"<br>";

			document.getElementById("output").innerHTML = str;
		}
		else
		{
			alert("error: "+response.error);
		}

    });

}
function load()
{
	//Get your own Browser API Key from  https://code.google.com/apis/console/
	gapi.client.setApiKey('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
	gapi.client.load('urlshortener', 'v1',function(){document.getElementById("output").innerHTML="";});

}
window.onload = load;

</script>
<script src="https://apis.google.com/js/client.js"> </script>

<body>

URL: <input type="text" id="longurl" name="url" value="http://www.hayageek.com" /> <br/>
<input type="button" value="Create Short" onclick="makeShort();" /> <br/> <br/>

URL: <input type="text" id="shorturl" name="url" value="http://goo.gl/NHj1c" /> <br/>
<input type="button" value="Get Short  URL Info" onclick="getShortInfo();" />

<div id="output">Wait. Loading....</div>

</body>
</html>

List of functions supported by URL Shortener JavaScript API.

a) .Creating Short URL

//Request Format:
var request = gapi.client.urlshortener.url.insert({
	  'resource': {
      'longUrl': "http://www.google.com/"
	}
    });

//JSON Response:
	{
	 "kind": "urlshortener#url",
	 "id": "http://goo.gl/fbsS",
	 "longUrl": "http://www.google.com/",
	 "status": "OK"
	}

 

b). Get the details/analytics of Short URL

//Request Format:
 var request = gapi.client.urlshortener.url.get({
		'shortUrl': "http://goo.gl/fbsS",
		'projection':'FULL'
   });

//projection can be 'FULL',"ANALYTICS_CLICKS" or "ANALYTICS_TOP_STRINGS"

//JSON Response
{
	"kind": "urlshortener#url",
	"id": "http://goo.gl/fbsS",
	"longUrl": "http://www.google.com/",
	"status": "OK"
}

Google URL Shortener API PHP Example

<?php
//Server Key
$apiKey = 'YOUR_SERVER_API_KEY';

//Long to Short URL
$longUrl = 'http://hayageek.com/google-url-shortener-api/';
$postData = array('longUrl' => $longUrl, 'key' => $apiKey);
$info = httpsPost($postData);
if($info != null)
{
	echo "Short URL is : ".$info->id."n";
}

//Short URL Information
$shortUrl="http://goo.gl/eDcZI";
$params = array('shortUrl' => $shortUrl, 'key' => $apiKey,'projection' => "ANALYTICS_CLICKS");
$info = httpGet($params);
if($info != null)
{
	echo "Long URL is : ".$info->longUrl."n";
	echo "All time clicks : ".$info->analytics->allTime->shortUrlClicks."n";

}

//Get Full Details of the short URL

$shortUrl="http://goo.gl/eDcZI";
$params = array('shortUrl' => $shortUrl, 'key' => $apiKey,'projection' => "FULL");
$info = httpGet($params);
var_dump($info);

function httpsPost($postData)
{
$curlObj = curl_init();

$jsonData = json_encode($postData);

curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);

$response = curl_exec($curlObj);

//change the response json string to object
$json = json_decode($response);
curl_close($curlObj);

return $json;
}

function httpGet($params)
{
$final_url = 'https://www.googleapis.com/urlshortener/v1/url?'.http_build_query($params);

$curlObj = curl_init($final_url);

curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));

$response = curl_exec($curlObj);

//change the response json string to object
$json = json_decode($response);
curl_close($curlObj);

return $json;
}
?>

For more documentation visit: https://developers.google.com/url-shortener/v1/url/get


I am a Developer. My motto: "Language is not a barrier" http://hayageek.com
All posts by Ravishanker Kusuma