Search code examples
google-apps-scriptgoogle-custom-search

UrlFetchApp request failing - Google Custom Search Engine API


I am trying to get results from my custom search engine(cse) via api using the Google Apps Script UrlFetchApp.fetch method. However, the url I am sending seems to be invalid. Will someone please tell me what I am doing wrong or if this is the wrong way to go about it?

function testGet(){  
  var q = "orell+auto"  
  var engID = "MY_ENGINE_ID"
  var cseAPIkey = "MY-KEY"  
  var response = UrlFetchApp.fetch("https://www.googleapis.com/customsearch/v1?&key="+ cseAPIkey + "&cx="+ engID +"q=" + q +"&fields=items(snippet%2Ctitle)%2Cspelling%2FcorrectedQuery");
  if (response.getResponseCode() == 200) {
    var text = response.getContentText();
    Logger.log(text);
  }
}

I don't have a particular reason for using the UrlFetchApp.fetch method, I just wanted the simplest way to call my cse from google apps script and return the corrected query, title, and snippet from the results (the last bit of the url).

Thanks!


Solution

  • So i found that there were a couple of errors in the url - one from my own key input and one in the url as it is shown. Here is the fixed line of code:

    var response = UrlFetchApp.fetch("https://www.googleapis.com/customsearch/v1?&key="+ cseAPIkey + "&cx="+ engID +"&q=" + q +"&fields=items(snippet%2Ctitle)%2Cspelling%2FcorrectedQuery");