google-apps-scriptgmail-apigmail-contextual-gadgetsgmail-addons

Permissions error using UrlFetchApp in Gmail Add-on


I am just starting to try building a new Gmail Add-on, and am running into the following error message:

"You do not have permission to call fetch"

This happens when testing the add-on in the Script Editor, and also when deployed inside my Gmail. Here is a sample of the code:

function getContextualAddOn(e) {
    var API_KEY = 'TESTKEY';
    var URL = 'https://[REDACTED]';
    var options = {
        'method' : 'post',
        'contentType': 'application/json',
        'headers': {
            'x-api-key': API_KEY
        },
        'payload' : JSON.stringify({ 'foo': 'bar' })
    };

    var response = UrlFetchApp.fetch(URL, options);

    [more code that builds a card] 
}

As you can see, it's a pretty straightforward use of UrlFetchApp.fetch. I'm brand new to Apps Script, so maybe I am missing some permissions declaration or scope in my manifest. I tried an even simpler example just using UrlFetchApp.getRequest, but that also failed with "You do not have permission to call getRequest".

The manifest for the addon is the same as in the examples:

{
  "timeZone": "America/New_York",
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER",

  "oauthScopes": [
    "https://www.googleapis.com/auth/gmail.addons.execute",
    "https://www.googleapis.com/auth/gmail.addons.current.message.readonly",
    "https://www.googleapis.com/auth/userinfo.email"
  ],
  "urlFetchWhitelist": [
    "https://[REDACTED]"
  ],
  "gmail": {
    "name": "Test Add-On",
    "logoUrl": "some url",
    "primaryColor": "#4285F4",
    "secondaryColor": "#4285F4",
    "contextualTriggers": [{
      "unconditional": {},
      "onTriggerFunction": "getContextualAddOn"
    }],
    "version": "TRUSTED_TESTER_V2"
  }
}

Is UrlFetchApp supposed to be allowed inside a Gmail Add-On, or is this just a bug? Do I need to add something to my manifest or enable some other option in the script editor?


Solution

  • The UrlFetchApp service requires an additional scope, https://www.googleapis.com/auth/script.external_request. Add it to your list of scopes and the code should work.

    The scopes required for each Apps Script method is listed under the "Authorization" section in the reference docs (example). Alternatively, you can discover the scopes required by your script by temporarily removing the oauthScopes section of the manifest and viewing the auto-determined scopes for your code in File > Project properties > Scopes. (If you define any scopes in your manifest, this disables the "automatic scope detection" behavior of Apps Script.)

    References