• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#
4# Copyright 2014 Google Inc. All Rights Reserved.
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#      http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
18"""Command-line sample for the Google URL Shortener API.
19
20Simple command-line example for Google URL Shortener API that shortens
21a URI then expands it.
22
23Usage:
24  $ python urlshortener.py
25
26You can also get help on all the command-line flags the program understands
27by running:
28
29  $ python urlshortener.py --help
30
31To get detailed log output run:
32
33  $ python urlshortener.py --logging_level=DEBUG
34"""
35from __future__ import print_function
36
37__author__ = 'jcgregorio@google.com (Joe Gregorio)'
38
39import pprint
40import sys
41
42from oauth2client import client
43from googleapiclient import sample_tools
44
45def main(argv):
46  service, flags = sample_tools.init(
47      argv, 'urlshortener', 'v1', __doc__, __file__,
48      scope='https://www.googleapis.com/auth/urlshortener')
49
50  try:
51    url = service.url()
52
53    # Create a shortened URL by inserting the URL into the url collection.
54    body = {'longUrl': 'http://code.google.com/apis/urlshortener/' }
55    resp = url.insert(body=body).execute()
56    pprint.pprint(resp)
57
58    short_url = resp['id']
59
60    # Convert the shortened URL back into a long URL
61    resp = url.get(shortUrl=short_url).execute()
62    pprint.pprint(resp)
63
64  except client.AccessTokenRefreshError:
65    print ('The credentials have been revoked or expired, please re-run'
66      'the application to re-authorize')
67
68if __name__ == '__main__':
69  main(sys.argv)
70