Archive
Posts Tagged ‘Google URL shortener’
Google’s URL shortener
June 25, 2013
Leave a comment
Problem
You want to shorten a long URL from the command line / from a script.
Solution
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/"
}
Exercise
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"]
Links
- Shorten a long URL @developers.google.com
Categories: python
curl, Google URL shortener, json, requests, url shortener