Shortening URLs for goo.gl with Google's URL Shortener API
In 2010 Google released its own URL shortener, which allows you to shorten URLs to use the goo.gl domain. In this article I will show you how to easily create your own short URLs using their new URL shortener API.
The Google URL Shortener API allows you to do the following:
- Create a new short URL
- Retrieve info about a short URL (such as the full URL and various analytics)
- Retrieve a list of shortened URLs for a given user
We will use the cURL library to perform the required HTTP requests to make use of this API. Additionally, JSON data is extensively used for both requests and responses, so we will use the json_encode() and json_decode() functions accordingly.
Creating an API Key
To use the Google URL Shortener API you must have an API key. To get an API, key, follow these instructions:
- Visit the Google APIs console
- Create a project
- Activate the URL Shortener API
- Click
Keysin the left navigation. You can then copy and paste the key from this page
Creating a Short URL
To create a shortened URL, post to https://www.googleapis.com/urlshortener/v1/url?key=key.
Rather than posting traditional form fields, we post JSON data instead. As such, we must also set the correct content type header for the request. Usually for post requests this is application/x-www-form-urlencoded, but we're posting JSON data so we use application/json.
To begin, let's define the API key and endpoint URL. The call we're making isn't the only API call available, so we define the base URL endpoint so it can be used for other calls too.
define('GOOGLE_API_KEY', '[insert your key here]'); define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');
Next, we define the shortenUrl function. This function accepts the long URL you want shortened and returns an array which holds the long and short URLs.
function shortenUrl($longUrl) { // initialize the cURL connection $ch = curl_init( sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY) ); // tell cURL to return the data rather than outputting it curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // ... more code will go here }
Here we initialize the cURL connection for our HTTP request. We build the URL from the endpoint and our API key and pass it as the first argument to curl_init().
Additionally, we set the CURLOPT_RETURNTRANSFER option to true. If we don't do this, we can't decode the returned JSON data. Instead, it will be output directly.
Next we must build the request data. As mentioned previously, the request must be a POST request which contains JSON data as the post body.
To create a new shortened URL, a single parameter called longUrl is required. The corresponding value should the URL to shorten. The following list demonstrates how we set the request to post JSON data.
function shortenUrl($longUrl) { // ... other code // create the data to be encoded into JSON $requestData = array( 'longUrl' => $longUrl ); // change the request type to POST curl_setopt($ch, CURLOPT_POST, true); // set the form content type for JSON data curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json')); // set the post body to encoded JSON data curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData)); // ... other code }
At this point, the cURL request is all set-up and ready to go. We can now excecute the request. The following listing demonstrates how to achieve this.
function shortenUrl($longUrl) { // ... other code // perform the request $result = curl_exec($ch); curl_close($ch); // decode and return the JSON response return json_decode($result, true); }
Since this web service returns JSON data, we can turn it into a native PHP array using json_docode(). The second argument of true instructs PHP to create an array (instead of an object).
Finally, we can make use of the shortenUrl() function simply by passing it a URL. We can then output the returned shortened URL. The following listing demonstrates how this is achieved.
$response = shortenUrl('http://phpriot.com'); echo sprintf( '%s was shortened to %s', $response['longUrl'], $response['id'] );
The Complete Code Listing
The complete listing we constructed in this article is as follows. Remember to substitute in your own API key.
define('GOOGLE_API_KEY', '[insert your key here]'); define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1'); function shortenUrl($longUrl) { // initialize the cURL connection $ch = curl_init( sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY) ); // tell cURL to return the data rather than outputting it curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // create the data to be encoded into JSON $requestData = array( 'longUrl' => $longUrl ); // change the request type to POST curl_setopt($ch, CURLOPT_POST, true); // set the form content type for JSON data curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json')); // set the post body to encoded JSON data curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData)); // perform the request $result = curl_exec($ch); curl_close($ch); // decode and return the JSON response return json_decode($result, true); } $response = shortenUrl('http://phpriot.com'); echo sprintf( '%s was shortened to %s', $response['longUrl'], $response['id'] );
Summary
In this article I showed you how to make use of the new Google URL Shortener API to generate your own short links on the goo.gl domain.
This API also allows you retrieve information and analytics about your shortened URLs. This requires only basic modifications to this script.
Further Reading
Other Options
- Download a PDF version of this article
- Put your PHP knowledge to the test with our online and iPad/iPhone quizzes
- View or post comments for this article
- Browse similar articles by tag: cURL, Google, JSON, PHP
- Read related articles:




