Google Sheets API

I’m trying to push a new entry from Google Sheets to Manager. Just to add a new customer that’s all for now.
However I’m getting an error code 401.
getManagerCustomer @ Code.gs:7
pushCustomerToManager @ Code.gs:15

Anyone have any idea? see script below. Thanks

// Function to fetch existing customers from Manager.io
function getManagerCustomer() {
  // Make API request to Manager.io to fetch customers
  // Replace 'YOUR_API_KEY' with your actual API key
  var apiKey = '####';
  var url = 'https://**.manager.io/api/****?api_key=' + apiKey;
  var response = UrlFetchApp.fetch(url);
  var data = JSON.parse(response.getContentText());
  return data;
}

// Function to push new customer names from Google Sheets to Manager.io
function pushCustomerToManager(customerName) {
  // Check if the customer already exists in Manager.io
  var existingCustomer = getManagerCustomer();
  var customerExists = existingCustomer.some(function(customer) {
    return customer.Name.toLowerCase() === customerName.toLowerCase();
  });
  
  if (customerExists) {
    Logger.log("Customer '" + customerName + "' already exists in Manager.io.");
    return;
  }
  
  // Create a new customer in Manager.io
  var newCustomer = createManagerCustomer(customerName);
  if (newCustomer) {
    Logger.log("Customer '" + customerName + "' successfully added to Manager.io.");
  } else {
    Logger.log("Failed to add customer '" + customerName + "' to Manager.io.");
  }
}

// Function to create a new customer in Manager.io
function createManagerCustomer(customerName) {
  // Make API request to Manager.io to create a new customer
  // Replace 'YOUR_API_KEY' with your actual API key
  var apiKey = '####';
  var url = 'https://**.manager.io/api/****?api_key=' + apiKey;
  var payload = {
    'Name': customerName
    // Add other necessary fields for creating a customer
  };
  var options = {
    'method': 'post',
    'contentType': 'application/json',
    'payload': JSON.stringify(payload)
  };
  var response = UrlFetchApp.fetch(url, options);
  var data = JSON.parse(response.getContentText());
  return data;
}

// Main function to iterate through new customer entries in Google Sheets and push them to Manager.io
function main() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("testsheet");
  var customerNames = sheet.getRange("A:A").getValues();
  
  for (var i = 1; i < customerNames.length; i++) {
    var name = customerNames[i][0];
    if (name) {
      pushCustomerToManager(name);
    }
  }
}

// Run the main function
function run() {
  main();
}

Hi @Arthur_Szilagyi,

It’s difficult to read through lots of unformatted scripts, so I’m not really sure what’s the root cause for this.

You can enclose your scripts with three grave accents ```, or use the </> Preformatted text button to post scripts.

See this discourse guide for more detail on that.

Anyway, back to the main topic. You’re basically getting an unauthorized error 401, which means there’s something wrong with the permissions.

The api2 is a newly added feature and the developer have said at one point that the access rights to the new api will be linked to the user permissions. Clearly we are not there yet.

You can still, however, use the old api to make POST requests and it will work provided you provide an administrator credentials.

Thanks @Ealfardan

I changed the code and simplified it (with help). For the moment I’m just trying to post/add a new customer named Arty. When running the code in Google Apps Script editor, I can see the existing customers (response from manager.io) in the execution log but it still doesn’t want to add/post Arty to customer list… It really doesn’t like me! maybe I’m just a bad customer :smiley:
See code below and let me know if i did something incorrect. Thanks

// Function to create a new customer in Manager.io with administrator credentials
function createManagerCustomerForTesting() {
  // Replace 'YOUR_USERNAME' and 'YOUR_PASSWORD' with your administrator credentials
  var username = 'admin';
  var password = 'password';
  
  // Encode credentials in Base64
  var credentials = Utilities.base64Encode(username + ':' + password);
  
  // Make API request to Manager.io to create a new customer
  var url = 'https://*domain*.manager.io/api/**busineskey**/**customerkey**.json';
  var payload = {
    "Name": "Arty"
    // Add other necessary fields for creating a customer
  };
  var options = {
    'method': 'post',
    'contentType': 'application/json',
    'payload': JSON.stringify(payload),
    'headers': {
      'Authorization': 'Basic ' + credentials
    }
  };
  
  try {
    // Send request
    var response = UrlFetchApp.fetch(url, options);
    var responseData = response.getContentText();
    console.log('Response:', responseData);
    var data = JSON.parse(responseData);
    return data;
  } catch (error) {
    console.error('Error creating customer:', error);
    return null;
  }
}

// Run the function to create a customer for testing
function testCreateCustomer() {
  createManagerCustomerForTesting();
}

I can’t find anything wrong with your latest script, however, the authorization isn’t required by Manager, it’s required by google. See this Google Developer Guide:

Thanks @Ealfardan

I tried without credential but I’m getting a 401 error.

Does anyone have any working script that posts data to manager.io? It doesn’t have to be creating customers, just something that i can use for reference? Thanks in advance.

@Ealfardan already explained that this is a Google auhthorization (token) issue and not Manager. Google says the following about 401 errors Resolve errors  |  Google Drive  |  Google for Developers.

That’s right, you need the credentials for Manager to accept the request and you need to comply with Google’s guidelines in order for Google to allow it.

But your second script is correct.

On another note, please disregard this:

I only said that assuming you got a 401 error using the api2. Since your original script contained an api key.

And since it seems like the Google only takes issue when using basic authentication, it’s possible that the api2 might work since it uses a different authentication method.

For the full schema of the api2, you can visit https://{ your domain }.manager.io/api2 and it should provide you with the possible routes and methods.

401 Unauthorized - HTTP | MDN (mozilla.org)

I have tried your script, it seems we cannot send POST via App script. I also tried the script I made, but this script always gives me a GET response.

Maybe there is a special trick so that App Script can send a POST?

I also tried converting App script to Excel macro, and it worked perfectly in Excel.

1 Like

@lubos, can you check this issue please?

I’m trying to pass a POST to the API using restapi-tester ,
it goes fine if I choose the Singapore - SG Location.
Other Locations will generate a GET response.

There seems to be a problem with the payload not delivered POST requests are converted into GET requests when redirecting URLs.
My server : https://{{subdomain}}.manager.io == https://{{subdomain}}.ap-southeast-1.manager.io

Location : Singapore - SG


Request Headers

POST /api/VGVzdEFQSTI/ec37c11e-2b67-49c6-8a58-6eccb7dd75ee.json HTTP/1.1
Authorization : Basic YWRtaW5pc3RyYXRvcjpCYWdvbmc=
User-Agent : Site24x7
Cache-Control : no-cache
Accept : */*
Connection : Keep-Alive
Accept-Encoding : gzip
Content-Type : application/json; charset=UTF-8
X-Site24x7-Id : 1420e1c1b70c
Content-Length : 38
Host : {{subdomain}}.manager.io


Response Headers


HTTP/1.1 200 OK
Date : Mon, 19 Feb 2024 04:56:00 GMT
Content-Type : application/json
Transfer-Encoding : chunked
Connection : keep-alive
Server : Kestrel
Cache-Control : no-cache, no-store
Content-Encoding : gzip
Location : /api/VGVzdEFQSTI/4cbf5271-3083-4250-b46b-2d3a7118e20e.json
Vary : Accept-Encoding


Response Body

{
  "Success": true,
  "Key": "4cbf5271-3083-4250-b46b-2d3a7118e20e"
}



From Others Location


Request Headers

POST /api/VGVzdEFQSTI/ec37c11e-2b67-49c6-8a58-6eccb7dd75ee.json HTTP/1.1
Authorization : Basic YWRtaW5pc3RyYXRvcjpCYWdvbmc=
User-Agent : Site24x7
Cache-Control : no-cache
Accept : */*
Connection : Keep-Alive
Accept-Encoding : gzip
Content-Type : application/json; charset=UTF-8
X-Site24x7-Id : 1420e1c1b70c
Content-Length : 38
Host : {{subdomain}}.manager.io

GET /api/VGVzdEFQSTI/ec37c11e-2b67-49c6-8a58-6eccb7dd75ee.json HTTP/1.1
Authorization : Basic YWRtaW5pc3RyYXRvcjpCYWdvbmc=
User-Agent : Site24x7
Cache-Control : no-cache
Accept : */*
Connection : Keep-Alive
Accept-Encoding : gzip
Content-Type : application/json; charset=UTF-8
X-Site24x7-Id : 1420e1c1b70c
Host : {{subdomain}}.ap-southeast-1.manager.io
Response Headers


HTTP/1.1 302 Found
Date : Mon, 19 Feb 2024 07:40:33 GMT
Content-Length : 0
Connection : keep-alive
Server : Kestrel
Location : https://{{subdomain}}.ap-southeast-1.manager.io/api/VGVzdEFQSTI/ec37c11e-2b67-49c6-8a58-6eccb7dd75ee.json

HTTP/1.1 200 OK
Date : Mon, 19 Feb 2024 07:40:34 GMT
Transfer-Encoding : chunked
Connection : keep-alive
Server : Kestrel
Access-Control-Allow-Headers : *
Access-Control-Allow-Methods : *
Access-Control-Allow-Origin : *
Cache-Control : no-cache, no-store
Response Body

[
  {
    "Key": "53030ec4-d31a-422c-a712-2a13ae6980d2",
    "Name": "First Customers",
    "Timestamp": 638439171761578100
  }
]




I think, the problem in this thread is in the location of the server where the App Script is run

1 Like

@Arthur_Szilagyi
It works fine today, we can consume the API via Google Scripts.

function sendDataToAPI() {
  // Ambil data dari Google Sheets
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var dataRange = sheet.getDataRange();
  var dataValues = dataRange.getValues();

  // Loop melalui setiap baris data
  for (var i = 1; i < dataValues.length; i++) { // Mulai dari indeks 1 untuk menghindari header
    var rowData = dataValues[i];
    var code = rowData[0];
    var name = rowData[1];

    var responseText="";

    // Buat objek JSON untuk dikirim ke API
    var payload = {
      "Code": code,
      "Name": name
    };

    // Konversi objek JSON menjadi string
    var payloadString = JSON.stringify(payload);

    // URL endpoint API
    var url ="https://{{subdomain}}.ap-southeast-1.manager.io/api/VGVzdEFQSTI/ec37c11e-2b67-49c6-8a58-6eccb7dd75ee.json";
    //var url = "https://{{subdomain}}.manager.io/api/VGVzdEFQSTI/ec37c11e-2b67-49c6-8a58-6eccb7dd75ee.json";

    // Buat options untuk request POST
    var options = {
      "method": "post",
      "payload":payloadString,
      "followRedirects": false,
      "headers": {
        "Content-Type" : "application/json; charset=UTF-8",
        "Authorization": "Basic " + Utilities.base64Encode("USERNAME:PASSWORD"), // Ganti USERNAME dan PASSWORD dengan kredensial Anda
      },
      "muteHttpExceptions":false
    };

console.log(JSON.stringify(options));

    // Kirim request POST ke API
    var response = UrlFetchApp.fetch(url, options);

    // Mendapatkan pesan respons dari API
     responseText = response.getContentText();
  
       // Cek response dari API
    if (response.getResponseCode() == 200) {
      Logger.log("Data berhasil dikirim: " + payloadString);
      Logger.log("Response: " + responseText);
    } else {
      Logger.log("Gagal mengirim data. Status code: " + response.getResponseCode());
      Logger.log("Response: " + responseText);
    }
  }
}

2 Likes

No success. I’m getting error code 302. If I set “followRedirects”: true. It says that data is successfully sent but when I check the new data is not there.

It worked!!! :smile: I used ap-southeast-2. Thank you so much @Mabaega