blob: f77a5f448e1f7e9e1b9ff767687d4363273b7768 [file] [log] [blame]
Joe Gregorio88243be2011-01-11 14:13:06 -05001#!/usr/bin/python2.4
2# -*- coding: utf-8 -*-
3#
4# Copyright 2010 Google Inc. All Rights Reserved.
5
6"""Simple command-line example for Google URL Shortener API.
7
8Command-line application that shortens a URL.
9"""
10
11__author__ = 'jcgregorio@google.com (Joe Gregorio)'
12
Joe Gregorio6abf8702011-03-18 22:44:17 -040013import gflags
14import httplib2
15import logging
Joe Gregorio88243be2011-01-11 14:13:06 -050016import pprint
Joe Gregorio6abf8702011-03-18 22:44:17 -040017import sys
Joe Gregorio88243be2011-01-11 14:13:06 -050018
Joe Gregorio6abf8702011-03-18 22:44:17 -040019from apiclient.discovery import build
20from oauth2client.file import Storage
21from oauth2client.client import OAuth2WebServerFlow
Joe Gregorio6abf8702011-03-18 22:44:17 -040022from oauth2client.tools import run
23
24FLAGS = gflags.FLAGS
25FLOW = OAuth2WebServerFlow(
26 client_id='433807057907.apps.googleusercontent.com',
27 client_secret='jigtZpMApkRxncxikFpR+SFg',
28 scope='https://www.googleapis.com/auth/urlshortener',
29 user_agent='urlshortener-cmdline-sample/1.0')
30
31gflags.DEFINE_enum('logging_level', 'ERROR',
32 ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
33 'Set the level of logging detail.')
Joe Gregorio88243be2011-01-11 14:13:06 -050034
35
Joe Gregorio6abf8702011-03-18 22:44:17 -040036def main(argv):
37 try:
38 argv = FLAGS(argv)
39 except gflags.FlagsError, e:
40 print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
41 sys.exit(1)
42
43 logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
44
45 storage = Storage('urlshortener.dat')
46 credentials = storage.get()
47 if credentials is None or credentials.invalid == True:
48 credentials = run(FLOW, storage)
49
50 http = httplib2.Http()
51 http = credentials.authorize(http)
Joe Gregorio88243be2011-01-11 14:13:06 -050052
53 # Build the url shortener service
Joe Gregorio6abf8702011-03-18 22:44:17 -040054 service = build("urlshortener", "v1", http=http,
Joe Gregorio88243be2011-01-11 14:13:06 -050055 developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0")
56 url = service.url()
57
58 # Create a shortened URL by inserting the URL into the url collection.
59 body = {"longUrl": "http://code.google.com/apis/urlshortener/" }
60 resp = url.insert(body=body).execute()
61 pprint.pprint(resp)
62
63 shortUrl = resp['id']
64
65 # Convert the shortened URL back into a long URL
66 resp = url.get(shortUrl=shortUrl).execute()
67 pprint.pprint(resp)
68
Joe Gregorio6abf8702011-03-18 22:44:17 -040069
Joe Gregorio88243be2011-01-11 14:13:06 -050070if __name__ == '__main__':
Joe Gregorio6abf8702011-03-18 22:44:17 -040071 main(sys.argv)