Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use Google Shortener API with Python

I want to write an app to shorten url. This is my code:

import urllib, urllib2
import json
def goo_shorten_url(url):
    post_url = 'https://www.googleapis.com/urlshortener/v1/url'
    postdata = urllib.urlencode({'longUrl':url})
    headers = {'Content-Type':'application/json'}
    req = urllib2.Request(
        post_url,
        postdata,
        headers
        )
    ret = urllib2.urlopen(req).read()
    return json.loads(ret)['id']

when I run the code to get a tiny url, it throws an exception: urllib2.HTTPError: HTTP Error 400: Bad Requests. What is wrong with this code?

like image 834
YuYang Avatar asked Jun 28 '13 04:06

YuYang


2 Answers

I know this question is old but it is high on Google.

Another thing to try is the pyshorteners library it is very simple to implement.

Here is a link:

https://pypi.python.org/pypi/pyshorteners

like image 54
John Raesly Avatar answered Sep 20 '22 09:09

John Raesly


With an api key:

import requests
import json

def shorten_url(url):
    post_url = 'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(API_KEY)
    payload = {'longUrl': url}
    headers = {'content-type': 'application/json'}
    r = requests.post(post_url, data=json.dumps(payload), headers=headers)
    return r.json()
like image 43
Sebastian Avatar answered Sep 22 '22 09:09

Sebastian