Update gs files from script using API

217 views Asked by At

Can you please tell me if it is possible to change the contents of the gs files of the same project from the google app script. This is required to receive code updates.

I am looking for opportunities to use the API, similar to how google clasp does it.

How realistic is it to do this?

[UPDATE]

Try this code:

  var scriptID = ScriptApp.getScriptId();
  var url = 'https://script.googleapis.com/v1/projects/' + scriptID + '/content';
  var token = ScriptApp.getOAuthToken();
  var options = {
    'method' : 'get',
    'headers' : {'Authorization':'Bearer '+  token},
    'muteHttpExceptions' : true
  };
  var response = UrlFetchApp.fetch(url, options);
  var json = JSON.parse(response.getContentText());
  Logger.log(json);

In Logger:

{error={details=[{domain=googleapis.com, @type=type.googleapis.com/google.rpc.ErrorInfo, reason=ACCESS_TOKEN_SCOPE_INSUFFICIENT, metadata={service=script.googleapis.com, method=google.apps.script.management.v1.ProjectsService.GetContent}}], message=Request had insufficient authentication scopes., code=403.0, status=PERMISSION_DENIED}}
1

There are 1 answers

1
Fernando Lara On

As Tanaike mentioned, you can in fact edit gs files from Google Apps Script using the Google Apps Script API.

Actually Google Clasp does use the Google Apps Script API to make the exact same type of changes.

You can take the following request as an example using the method projects.updateContent to make a simple change in the source parameter. In addition to that, you need to make sure that the Google Apps Script API is enabled from your Apps Script Settings, and not only add the gs file you want to send in the request, but also the appsscript.json file from the manifest is required in the request.

{
  "files": [
    {
      "name": "appsscript",
      "type": "JSON",
      "source": "{\n  \"timeZone\": \"America/El_Salvador\",\n  \"dependencies\": {},\n  \"exceptionLogging\": \"STACKDRIVER\",\n  \"runtimeVersion\": \"V8\"\n}"
    },
    {
      "name": "Code",
      "type": "SERVER_JS",
      "source": "function myFunction() {\n  Logger.log(\"This is a test\");\n}\n",
      "functionSet": {
        "values": [
          {
            "name": "myFunction"
          }
        ]
      }
    }
  ]
}

References: