GitHub with Google Apps Script

Thisara Welmilla
2 min readAug 24, 2021

--

With Google Apps Script, we can implement custom functions, menus or create and publish add-ons for Google Workspace applications like Google Docs, Google Sheets etc.

This article will guide you how to use GitHub APIs (https://docs.github.com/en/rest/reference) with Google Apps Script. As an example let’s take a scenario where we are going to retrieve the content of a GitHub repository file.

Step 1

First Go to the Google Apps Script editor.

You can follow steps in the official guide https://developers.google.com/apps-script/overview#set_it_up.

or

To have an document embedded script, go to the relevant document (a Doc or Sheet) and Menu Bar — > Tools — > Script Editor.

Step 2

If the repository is private, then we will need a GitHub access token. If the repository is public, you can skip this step.

  1. Get a GitHub access token from a GitHub account which has required permissions to access the relevant GitHub repository. Follow the official guide to obtain a access token. https://docs.github.com/en/github/authenticating-to-github/keeping-your-account-and-data-secure/creating-a-personal-access-token
  2. Store it the token in a secure manner as following.
PropertiesService.getScriptProperties().setProperty(AUTH_TOKEN, <tokenValue>);

3. You can create a pop up window which will be available at menu bar to take the access token as a user input.

function onOpen() {    var ui = SpreadsheetApp.getUi();
ui.createMenu('Admin Actions').addItem('Update token',
'updateAuthToken').addToUi();
}

function updateAuthToken() {
var ui = SpreadsheetApp.getUi();
var tokenInput = ui.prompt("Please enter the auth token");
var tokenValue = tokenInput.getResponseText();
if (isEmpty(tokenValue)) {
ui.alert("Token cannot be empty");
return;
}
PropertiesService.getScriptProperties().setProperty(AUTH_TOKEN,
tokenValue);
}

Step 3

  1. Set the Git API URL to a variable as bellow. We will use this variable in the next step.
const GIT_API_URL = 'https://api.github.com/repos/<REPOSITORY_OWNER>/<REPOSITORY_NAME>/content/<REPOSITORY_PATH_BUILD>?ref=<REPOSITORY_BRANCH>/<FILE_NAME>';

Sample GitHub API URL:

https://api.github.com/repos/Thisara-Welmilla/AppsScript-Examples/content/Sample-Codes?ref=master/GitWithAppsScript.js

2. As the last part of this step, send a API request to get the file content.

var urlFetchOptions = {
"method": "GET",
"headers": {
"Accept": "application/vnd.github.v3+json",
"Content-Type": "application/json",
"Authorization": `Bearer ${getGitToken()}`
}
}
var gitResponse = UrlFetchApp.fetch(GIT_API_URL, urlFetchOptions);

We can retrieve the get token which we stored in in the step 2 with following code segment.

function getGitToken() {
PropertiesService.getScriptProperties().getProperty(AUTH_TOKEN);
}

To try another GitHub API, all you need to do is change the `GIT_API_URL` and `urlFetchOptions`according the GitHub API and all set to go.

Happy reading!

--

--