blob: 62945c5832e05d536828ded16985cff12a3be09f [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
22from oauth2client.client import AccessTokenCredentials
23from oauth2client.tools import run
24
25FLAGS = gflags.FLAGS
26FLOW = OAuth2WebServerFlow(
27 client_id='433807057907.apps.googleusercontent.com',
28 client_secret='jigtZpMApkRxncxikFpR+SFg',
29 scope='https://www.googleapis.com/auth/urlshortener',
30 user_agent='urlshortener-cmdline-sample/1.0')
31
32gflags.DEFINE_enum('logging_level', 'ERROR',
33 ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
34 'Set the level of logging detail.')
Joe Gregorio88243be2011-01-11 14:13:06 -050035
36
Joe Gregorio6abf8702011-03-18 22:44:17 -040037def main(argv):
38 try:
39 argv = FLAGS(argv)
40 except gflags.FlagsError, e:
41 print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
42 sys.exit(1)
43
44 logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
45
46 storage = Storage('urlshortener.dat')
47 credentials = storage.get()
48 if credentials is None or credentials.invalid == True:
49 credentials = run(FLOW, storage)
50
51 http = httplib2.Http()
52 http = credentials.authorize(http)
Joe Gregorio88243be2011-01-11 14:13:06 -050053
54 # Build the url shortener service
Joe Gregorio6abf8702011-03-18 22:44:17 -040055 service = build("urlshortener", "v1", http=http,
Joe Gregorio88243be2011-01-11 14:13:06 -050056 developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0")
57 url = service.url()
58
59 # Create a shortened URL by inserting the URL into the url collection.
60 body = {"longUrl": "http://code.google.com/apis/urlshortener/" }
61 resp = url.insert(body=body).execute()
62 pprint.pprint(resp)
63
64 shortUrl = resp['id']
65
66 # Convert the shortened URL back into a long URL
67 resp = url.get(shortUrl=shortUrl).execute()
68 pprint.pprint(resp)
69
Joe Gregorio6abf8702011-03-18 22:44:17 -040070
Joe Gregorio88243be2011-01-11 14:13:06 -050071if __name__ == '__main__':
Joe Gregorio6abf8702011-03-18 22:44:17 -040072 main(sys.argv)