3

I'm trying to query the goo.gl API from inside a Google Apps Script. The problem I'm seeing is the following error message:

Request failed for https://www.googleapis.com/urlshortener/v1/url?key=AIXXXXXXXXXXXXXXXXXXXXXLmGJQw returned code 400. Server response: { "error": { "errors": [ { "domain": "global", "reason": "parseError", "message": "This API does not support parsing form-encoded input." } ], "code": 400, "message": "This API does not support parsing form-encoded input." } } (line 28)

the message comes up when I try to do the actual request at UrlFetchApp.fetch(post_url, options);.

Here's the actual coding I'm using in Google Apps Script.

function minifyGoogl(longUrl) {
  var post_url = 'https://www.googleapis.com/urlshortener/v1/url';

  var apiKey = UserProperties.getProperty('googl_api_key');

  if(!apiKey){
    var apiKey = ScriptProperties.getProperty('googl_api_key');
  }

  if(apiKey){
    post_url += '?key=' + apiKey;
  }

  var payload = Utilities.jsonStringify({'longUrl': longUrl });

  var options = {
    'method' : 'post',
    'headers' : {
      'Content-Type' : 'application/json'
    },
    'payload' : payload
  };

  try{
    var response = UrlFetchApp.fetch(post_url, options);
  }catch(e){
    if(e.message){
      throw e.message;
    }
  }

  var responseJson = response.getAs('json');
}
function testMinifyGoogl(){
  minifyGoogl('http://eduardo.cereto.net');
}
Eduardo
  • 22,574
  • 11
  • 76
  • 94

2 Answers2

3

The documentation says the contentType defaults to 'application/x-www-form-urlencoded'.

Perhaps try setting the Content-Type with the contentType argument rather than inserting a Content-Type header manually?

sarnold
  • 102,305
  • 22
  • 181
  • 238
  • Thanks, that is exactly what I needed. I didn't see that `contentType` parameter. And tried to set it myself using the HTTP header parameter. – Eduardo Jul 04 '11 at 01:41
  • That fixed it for me. The lib I was using wanted me to manually JSON.stringify my request body. This pointed me in the right direction. Thanks! – frosty May 23 '13 at 10:07
0

The following code works perfectly.

function ShortenUrl(){
var url = 'https://www.googleapis.com/urlshortener/v1/url';
var apiKey = 'AIzBlNS-3HZdxKgwj-x30';
url += '?key=' + apiKey;
var payload = {"longUrl":"www.google.com"};

var parameters = { method : 'post',
                payload:JSON.stringify(payload),
                contentType:'application/json',                    
                muteHttpExceptions:true};

var response = UrlFetchApp.fetch(url, parameters);
Logger.log(response);
}