I wrote a Google sheet app script that requires some API calls. When I run the script within App Script editor, it runs fine.
But when I call the formula from within Google Sheets, then it throws an error saying "invalid API key" while I know that API is correct.
const api_key = "";
const response = UrlFetchApp.fetch("https://serpapi.com/search.json?q=" + keyword
+"&hl="+"&gl="+location+"&num=100"+ "&engine = Google" +
"&google_domain=google.co.uk"+"&api_key="+api_key);
Here is the whole script
function GetRank(keyword, domain, location) {
const response = UrlFetchApp.fetch("https://serpapi.com/search.json?q=" + keyword +"&hl="+"&gl="+location+"&num=100"+ "&engine = Google" + "&google_domain=google.co.uk"+"&api_key=xxx-xxx-xxx");
const json = response.getContentText();
const results = JSON.parse(json);
const final = results.organic_results;
for(let i = 0; i< final.length; i++){
rank = 'Not in Top 100';
links = final[i].link;
if(links.includes(domain)){
rank = final[i].position;
show = final[i].link;
break;
}
}
console.log(rank, show);
return [rank, show];
}