What is the URL Shortener API?
The Google URL Shortener at goo.gl is a service that takes long URLs and squeezes them into fewer characters to make a link that is easier to share, tweet, or email to friends.
This tutorial includes 2 main parts: Shorten long URLs and expand shortened URLs.
1. Shorten a long URL: allows you to shorten any long URL, ex: from http://4rapiddev.com/google-api/php-example-google-url-shortener-api/ to http://goo.gl/Ct4Nc
2. Expand a short URL: allows you to expand any short URL, ex: from http://goo.gl/Ct4Nc to http://4rapiddev.com/google-api/php-example-google-url-shortener-api/
Note: for every API call, you should Provide an API key which is highly recommended to get a higher usage limits & traffic analytics report.Getting a key from APIs Console.
Example & demo will be posted later, I’m reviewing their API and will post an example very shortly.
[php] <?php// Declare the class
class GoogleUrlApi {
// Constructor
function GoogleURLAPI($key,$apiURL = ‘https://www.googleapis.com/urlshortener/v1/url’) {
// Keep the API Url
$this->apiURL = $apiURL.’?key=’.$key;
}
// Shorten a URL
function shorten($url) {
// Send information along
$response = $this->send($url);
// Return the result
return isset($response[‘id’]) ? $response[‘id’] : false;
}
// Expand a URL
function expand($url) {
// Send information along
$response = $this->send($url,false);
// Return the result
return isset($response[‘longUrl’]) ? $response[‘longUrl’] : false;
}
// Send information to Google
function send($url,$shorten = true) {
// Create cURL
$ch = curl_init();
// If we’re shortening a URL…
if($shorten) {
curl_setopt($ch,CURLOPT_URL,$this->apiURL);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
}
else {
curl_setopt($ch,CURLOPT_URL,$this->apiURL.’&shortUrl=’.$url);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// Execute the post
$result = curl_exec($ch);
// Close the connection
curl_close($ch);
// Return the result
return json_decode($result,true);
}
}
// Create instance with key
$key = ‘AIzaSyBhdyvJn6YCG8h-_F5YhoQwtfNLtsHX4Ds’;
$googer = new GoogleURLAPI($key);
// Test: Shorten a URL
$shortDWName = $googer->shorten("http://davidwalsh.name");
echo $shortDWName; // returns http://goo.gl/i002
// Test: Expand a URL
$longDWName = $googer->expand($shortDWName);
echo $longDWName; // returns http://davidwalsh.name
?>
[/php]