API Authentication Apps Script Reference

This post is a summary of common authentication protocols for API authentication with Apps Script.

I got fed up digging around in my Drive folder for old scripts to refresh my memory on the syntax, so I created this reference.

It’s not a comprehensive post on how to connect to APIs, instead, it’s a short summary of common protocols for easy reference.(If you’re new to APIs, start with my Apps Script API tutorial for beginners.)

This post looks at four different API authentication methods:

  1. No API authentication
  2. Requires API key in query string
  3. Requires API key in header
  4. OAuth2: Secure API authentication

Does coding fill you with dread? In that case, you can still achieve your goals using a no-code option to sync live data into Google Sheets. Check out Coefficient’s sidebar extension that offers Google Sheets connectors for CRMs, BI tools, databases, payment platforms, and more.*

1. No API Authentication

This is not common, but there are some APIs that don’t require any authentication (e.g. the Numbers API).

It’s a bit like leaving the door of your house permanently open though, so it’s not good practice if you have anything valuable inside. However, it’s ok for some APIs (like the Numbers example I just mentioned) because they don’t have any personal data behind them.

The Apps Script code to call an API with no authentication will look something like this, where “url” is the API URL you are calling:

// set the endpoint
const url = 'https://developers.example.com/v1/abc';

// call the API
const response = UrlFetchApp.fetch(url);

2. Requires API Key in Query String

These APIs require an API Key to get access. It is passed as part of the query string.

For example, the code for this type of API Authentication might look like this:

// include the API Key
const API_KEY = 'XXXXXXXXXXXXXXX';

// set the endpoint
const url = 'https://developers.example.com/v1/abc';

// call the API
const response = UrlFetchApp.fetch(url + '&api_key=' + API_KEY);

The ConvertKit API uses this method of authentication with the query string, and I used it to build an automated ConvertKit report.

3. Requires API Key in Header

This is another simple API Authentication method.

You supply the API Key in the headers object, inside the params object, and then pass that to the UrlFetchApp class:

// include the API Key
const API_KEY = 'XXXXXXXXXXXXXXX';

// set the endpoint
const url = 'https://developers.example.com/v1/abc';

// set the params object
const params = {
    headers: {
      Authorization: API_KEY
    }
  }

// call the API
const response = UrlFetchApp.fetch(url,params);

Sometimes the word “Authorization” is replaced with a different word, depending on how the API designers have set the API up.

For example, the Teachable API uses the word “apiKey” instead (see line 10):

// include the API Key
const API_KEY = 'XXXXXXXXXXXXXXX';

// set the endpoint
const url = 'https://developers.example.com/v1/abc';

// set the params object
const params = {
    headers: {
      apiKey: API_KEY
    }
  }

// call the API
const response = UrlFetchApp.fetch(url,params);

Params Object Syntax

Note, the params object can include other, optional advanced parameters. For example:

// set up the parameters
const params = {
  headers: {
    Accept: 'application/json',
    Accept-Language: 'en_US',
    Authorization: API_KEY
  },
  method: 'post',
  payload: {
    grant_type: 'client_credentials'
  },
  muteHttpExceptions: true
}

For more details, see the UrlFetchApp.fetch(url,params) documentation.

4. OAuth 2: Secure API Authentication

Finally, the most secure API Authentication presented here is to use the OAuth2 protocol.

It’s a standard way of granting web applications access to your data from other web applications, without you needing to enter your username/passwords.

In other words, the web applications can talk to each other programmatically, without you needing to authorize it every time.

In this scenario, the code to call the API would look something like this:

// get the Facebook Service
const xyzService = getXYZService();
  
// get the access token
const ACCESS_TOKEN = xyzService.getAccessToken();

// set the endpoint
const url = 'https://developers.example.com/v1/abc';

// set the params object
const params = {
    headers: {
      Authorization: 'Bearer ' + ACCESS_TOKEN
    }
  }

// call the API
const response = UrlFetchApp.fetch(url,params);

However, this only shows the API call.

More code is required to create the OAuth2 service (which I’ve called getXYZService) that generates the access token. More details here.

To illustrate, here’s an example Apps Script API using the OAuth2 protocol to retrieve data from GitHub.

* Disclosure: Some of the links in this post are affiliate links, meaning I’ll get a small commission if you click the link and subsequently signup to use that vendor’s service. I only do this for tools I use myself and wholeheartedly recommend.

5 thoughts on “API Authentication Apps Script Reference”

    1. Yann, do this:

      // include the API Key
      const API_KEY = “Basic ” + Utilities.base64Encode(‘username:password’);

    2. A little late here, but if you’re trying to authenticate via API key with Toggle (and not `username:password`) you’ll need to encode the API key string and pass it as basic auth, like so:
      “`
      // Get your API key from Toggl
      const YOUR_API_KEY = “xxxxxxxxxx”;

      // Base64 encode the API key string and add as “Basic” auth
      const API_KEY = “Basic ” + Utilities.base64Encode( YOUR_API_KEY + “:api_token” );

      // Add to request headers
      const params = {
      headers: {
      Authorization: API_KEY,
      ContentType: “application/json”
      }
      }

      const response = UrlFetchApp.fetch(url ,params);
      “`

  1. I’m not sure which of these cases would apply to using the Google People API in Apps Script. I was able to create a key on Google’s API console (I think) but I have no idea how to pass it with my query.

    Oddly, if I run a script from the editor that makes a People API query, the query works fine. When I try to run it from an event trigger, it complains about Oauth

Leave a Reply

Your email address will not be published. Required fields are marked *