11

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?

lehins
  • 9,642
  • 2
  • 35
  • 49
YuYang
  • 321
  • 5
  • 11

3 Answers3

15

I tried your code and couldn't make it work either, so I wrote it with requests:

import requests
import json

def goo_shorten_url(url):
    post_url = 'https://www.googleapis.com/urlshortener/v1/url'
    payload = {'longUrl': url}
    headers = {'content-type': 'application/json'}
    r = requests.post(post_url, data=json.dumps(payload), headers=headers)
    print(r.text)

Edit: code working with urllib:

def goo_shorten_url(url):
    post_url = 'https://www.googleapis.com/urlshortener/v1/url'
    postdata = {'longUrl':url}
    headers = {'Content-Type':'application/json'}
    req = urllib2.Request(
        post_url,
        json.dumps(postdata),
        headers
    )
    ret = urllib2.urlopen(req).read()
    print(ret)
    return json.loads(ret)['id']
PepperoniPizza
  • 8,842
  • 9
  • 58
  • 100
  • thanks for your reply.The API of urllib and urllib2 is really ugly.actually, I have written the app with requests and it works too,but why should I replace urllib.urlencode with json.dumps? – YuYang Jun 28 '13 at 05:56
  • because `urlencode` passes key:value separated by & and what google API is expecting is a json like data {key:value}. [urlencode] (http://docs.python.org/2/library/urllib.html#urllib.urlencode) – PepperoniPizza Jun 28 '13 at 14:18
  • 1
    in your answer I've found my solution: I was using 'params' instead of 'data' in requests.post() – Jonatas CD Sep 29 '15 at 05:15
  • @eugene you can find here how to get the key: https://developers.google.com/url-shortener/v1/getting_started#APIKey – Jonatas CD Sep 29 '15 at 05:16
5

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

Jonatas CD
  • 878
  • 2
  • 10
  • 19
John Raesly
  • 308
  • 4
  • 11
5

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()
Sebastian
  • 1,623
  • 19
  • 23