Search code examples
pythonjsonapigoogle-url-shortener

Error with Google Shortener API and Python


I am making an app which works with urls and I need to shorten them. I have written the following code:

import requests, json
gUrl = 'https://www.googleapis.com/urlshortener/v1/url'
data = json.dumps({'longUrl': 'http://www.google.es'})
r = requests.post(gUrl, data)

It is supposed to be encoded with json, nevertheless, I am getting the following error:

print r.json
{u'error': {u'code': 400, u'message': u'This API does not support parsing form-encoded
input.', u'errors': [{u'domain': u'global', u'message': u'This API does not support
parsing form-encoded input.', u'reason': u'parseError'}]}}

Other information that may be useful:

print r.request
Request [POST]


print r.headers
{'x-xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff',
'transfer-encoding': 'chunked', 'expires': 'Thu, 05 Jul 2012 20:47:11 GMT',
'server': 'GSE', 'cache-control': 'private, max-age=0', 
'date': 'Thu, 05 Jul 2012 20:47:11 GMT', 'x-frame-options': 'SAMEORIGIN', 
'content-type': 'application/json; charset=UTF-8'}

Thank you very much in advance.


Solution

  • You need to make sure that Content-Type: application/json is being sent, else the POST data is form encoded.

    eg r = requests.post(gUrl, data, headers={'Content-Type': 'application/json'})

    print r.json - outputs:

    {u'kind': u'urlshortener#url', u'id': u'http://goo.gl/5Af0', u'longUrl': u'http://www.google.es/'}