Home > python > Google’s URL shortener

Google’s URL shortener

You want to shorten a long URL from the command line / from a script.

There are lots of URL shorteners. With the Google URL shortener you can do it like this:

curl https://www.googleapis.com/urlshortener/v1/url -H 'Content-Type: application/json' -d '{"longUrl": "https://ubuntuincident.wordpress.com"}'

Sample output:

    "kind": "urlshortener#url",
    "id": "http://goo.gl/Zeigx",
    "longUrl": "https://ubuntuincident.wordpress.com/"

Let’s do it in Python using the requests module:

import requests
import json

url = "https://www.googleapis.com/urlshortener/v1/url"
data = {"longUrl": "https://ubuntuincident.wordpress.com"}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)
print r.text
print 'Short URL:', r.json()["id"]


  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: