Skip to content

Instantly share code, notes, and snippets.

@benjyiw
Created May 19, 2018 02:57
Show Gist options
  • Select an option

  • Save benjyiw/2ee9efee4629939b22cec8f5ce857fda to your computer and use it in GitHub Desktop.

Select an option

Save benjyiw/2ee9efee4629939b22cec8f5ce857fda to your computer and use it in GitHub Desktop.
python url shortener with goo.gl
#!/usr/bin/env python
# Get a Google API from here:
# https://console.developers.google.com/projectselector/apis/credentials?pli=1
import argparse
import json
import requests
GOOGLE_URL_SHORTEN_API = ''
parser = argparse.ArgumentParser(description='Shorten URL with goo.gl')
parser.add_argument('url', metavar='url', help='URL to be shortened')
def google_url_shorten(url):
req_url = 'https://www.googleapis.com/urlshortener/v1/url?key=' + GOOGLE_URL_SHORTEN_API
payload = {'longUrl': url}
headers = {'content-type': 'application/json'}
r = requests.post(req_url, data=json.dumps(payload), headers=headers)
resp = json.loads(r.text)
return resp['id']
args = parser.parse_args()
print(google_url_shorten(args.url))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment