The two minute tutorial on using the Google URL Shortener API (with PHP)

Post to Twitter

Google recently introduced an API to use their URL shortening service. Today I’m going to quickly demo how you can use cURL with PHP to call the API. If you read over the getting started document you will see you can create a project in which you can call this API much more frequently using an API key generated for you so Google knows whom is calling their service, etc. (you should do this in a production environment obviously). To keep it simple I’ll leave out the API key and simply make a quick cURL call to the API to demo how to use this very simple service.

According to the documentation we need to send a cURL request with the following details:

POST https://www.googleapis.com/urlshortener/v1/url
Content-Type: application/json

{"longUrl": "http://www.insert-your-url-here.com/"}

Crafting up some quick PHP code I found this worked:

<?php
  $longURLData = array('longUrl' => 'http://giantflyingsaucer.com/blog');

  $curl = curl_init();
  curl_setopt($curl, CURLOPT_POST, 1);
  curl_setopt($curl, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($longURLData));
  $jsonResult = curl_exec($curl);
  curl_close($curl);
 
  $resultArray = json_decode($jsonResult, true);
  
  echo '<br />Shortened URL: ' . $resultArray['id'];
  echo '<br /><br />JSON: ' . $jsonResult;
?>

The result coming back was:

Shortened URL: http://goo.gl/zPwcM

JSON: { "kind": "urlshortener#url", "id": "http://goo.gl/zPwcM", "longUrl": "http://giantflyingsaucer.com/blog" } 

When you want to use an API key simply modify the URL like so:

curl_setopt($curl, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url?key=<your_key>');

Post to Twitter

This entry was posted in PHP. Bookmark the permalink.

5 Responses to The two minute tutorial on using the Google URL Shortener API (with PHP)

  1. Pingback: The two minute tutorial on using the Google URL Shortener API (with PHP)

  2. Pingback: Tweets that mention The two minute tutorial on using the Google URL Shortener API (with PHP) -- Topsy.com

  3. Pingback: Using the Google URL Shortener API with ASP.NET MVC 3 and C# | Giant Flying Saucer

  4. Thanks.
    Since I’m kind of a php newbie, this was very useful.

  5. Alex Stomp says:

    Thank you! The actual php request code is something i’m unfamiliar with, and this saved me A LOT of time!

Comments are closed.