Google Apps Script - URL Fetch App returning random numbers

Viewed 43

I am new to Apps Script and was trying to build an API and call that API through a different script. I created the web app and published it.

This is the URL: https://script.google.com/macros/s/AKfycbxKVmGy3fxDfoHxyDtQh7psqj7IdKF7qHbgxLAwNRoiKTA-bpKN4QKtArzwsYdFb-Hb/exec

When I open this link, I can see the data correctly but when I try to fetch this data from a different script using urlfetchapp, it returns random numbers. I need help on what I am doing incorrectly.

Script which I am using to call this data:

function GetCopies()
{
  var options = {
  'contentType': "application/json",
  'method' : 'get',
  };
  var Data = UrlFetchApp.fetch('https://script.google.com/macros/s/AKfycbxKVmGy3fxDfoHxyDtQh7psqj7IdKF7qHbgxLAwNRoiKTA-bpKN4QKtArzwsYdFb-Hb/exec',options)

  Logger.log(Data.getContent())
  
}

This is the log I get:

Logs for data without json parse

I tried parsing it, but it throws an error:

Error when parsed

How can I get data from URL correctly?

1 Answers

A working sample:

  1. Create two Google Apps Script projects. In my case API and fetcher
API
const doGet = () => {
  const myObj = {
    "name": "Mr.GAS",
    "email": "mrgas@blabla.com"
  }
  return ContentService
    .createTextOutput(JSON.stringify(myObj))
    .setMimeType(
      ContentService.MimeType.JSON
    )
}
fetcher
const LINK = "API_LINK"

const fetchTheAPI = async () => {
  const options = {
    'contentType': "application/json",
    'method': 'get',
  }
  const res = UrlFetchApp.fetch(LINK, options)
  const text = res.getContentText()
  console.log(JSON.parse(text))
}
  1. Deploy the API: Select type > Web app and Who has access > Anyone, copy the URL (it is important to copy that URL not the one redirected in the browser)
  2. Replace the "API_LINK" by the URL.
  3. Run the function.

You only need to adapt this example to suit your needs.

Documentation:
Related