Quick Integration Method for Google Apps Script x Google APIs
Using Google Apps Script x Firebase App Distribution API as an example
ℹ️ℹ️ℹ️ The following content is translated by OpenAI.
Click here to view the original Chinese version. | 點此查看本文中文版
Quick Integration Method for Google Apps Script x Google APIs
Using Google Apps Script x Firebase App Distribution API as an example
Background
Previously, I wrote several articles about using Google Apps Script, including “Implementing Daily Data Report RPA Automation with Google Apps Script” and “Simple 3 Steps — Create a Free GA4 Automatic Data Notification Bot,” which introduced how to use Google Apps Script to connect Google Analytics and Google Sheets, Web Apps, Slack, Telegram, etc., to quickly build a visual data platform and notification service. Additionally, last month’s article “Using Google Apps Script Web App Forms to Connect to GitHub Action CI/CD” directly used Google Apps Script Web App to connect to the GitHub API as a CI/CD GUI form service. In all these cases, whether directly using the built-in services of Google Apps Script for integration or connecting to external services (Slack, GitHub, etc.), I hadn’t encountered a scenario that required connecting to Google APIs.
This time, while optimizing the CI/CD GUI form, I wanted to display the Firebase Distribution download link directly on the Web App after packaging the internal test version, which could only be achieved by connecting to Google APIs.
Google Apps Script x Firebase App Distribution API v1
As shown in the image above, unlike the built-in service “AnalyticsData” for connecting to Google Analytics, Firebase App Distribution does not provide a built-in integration service, so we need to use an advanced method for integration.
I initially thought I would have to generate and exchange the Access Token using a Service Account (which is a bit cumbersome; you can refer to my previous review bot open-source project), but it turns out it’s not that complicated.
Advanced Service Integration of Google Apps Script x Google APIs
Integration Setup
Refer to the official documentation for the following advanced setup steps:
- You must enable advanced services in your script project.
- You must ensure that the API for the corresponding advanced service is enabled in the Cloud Platform (GCP) project used by the script.
- If the script project uses a default GCP project created on or after April 8, 2019, the API will be automatically enabled after you enable advanced services and save the script project. If you have not agreed yet, the system may also prompt you to agree to the Google Cloud and Google API terms of service.
- If the script project uses a standard GCP project or an older default GCP project, you must manually enable the corresponding API for advanced services in the GCP project. You must have edit permissions for the GCP project to make this change.
1. Project Setup — Associate with Google Cloud Platform (GCP) Project
The advanced service integration of Google Apps Script x Google APIs requires you to create a GCP project and associate it with Google Apps Script. The permissions for using Google APIs are based on the GCP settings.
Therefore, you need to create a GCP project (the same Firebase GCP project is also acceptable), note the “ Project Number
“ on the information homepage, and ensure that this GCP project has enabled the Google APIs you want to use and that the currently logged-in account or the account you wish to use has permissions for that GCP project and Google APIs.
This article uses the “Firebase App Distribution API” as an example.
Enter the Project Number
into the Google Cloud Platform project number field at the bottom of the Google Apps Script project settings. If the currently logged-in account has permissions for that GCP project, it will automatically bind and set up successfully.
2. Project Setup — Enable Display of “appsscript.json” Manifest File in the Editor
After enabling, return to the editor, and the file list will show the “ appsscript.json
“ configuration file:
Ensure that the oauthScopes includes the following two configuration settings:
1
2
3
4
"oauthScopes": [
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/cloud-platform"
]
If not, please manually paste and save.
3. Write Integration Code
After setting up the GCP project, we can start writing the integration code. Directly refer to the official documentation of the Google APIs you want to connect to, Firebase App Distribution API v1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const project = "projects/[Firebase Project ID]/apps/[Firebase APP ID]"; // Please replace with your Project ID & App ID
function debug() {
const releases = firebaseDistribution("");
releases.forEach(function(release) {
// Release Object: https://firebase.google.com/docs/reference/app-distribution/rest/v1/projects.apps.releases?hl=zh-tw#Release
Logger.log(`${release.name} Download URL: ${release.testingUri}`);
});
}
function firebaseDistribution(releaseNote) {
const url = "https://firebaseappdistribution.googleapis.com/v1/"+project+"/releases?filter=releaseNotes.text%3D*"+releaseNote+"*";
// Filter: https://firebase.google.com/docs/reference/app-distribution/rest/v1/projects.apps.releases/list?hl=zh-tw
const headers = {
"Content-Type": "application/json; charset=UTF-8",
"Authorization": "Bearer " + ScriptApp.getOAuthToken(), // Directly use the current account to obtain the token
};
const options = {
"method": "get",
"headers": headers
};
const data = UrlFetchApp.fetch(url, options);
const result = JSON.parse(data.getContentText()).releases;
if (result == undefined) {
return [];
}
return result;
}
[Firebase Project ID]
and [Firebase APP ID]
can be obtained from the Firebase project settings:
After pasting the code, the first execution requires completing permission authorization.
- Click “Review Permissions”
- Select the account to execute, usually the current Google Apps Script account
- Choose “Advanced” to expand -> Click “Go to XXX” This is an application we wrote for our own use, so it doesn’t need to go through Google verification.
- Click “Allow”
The above screens may not appear; if they don’t, you can ignore them.
After allowing, clicking “Debug” or “Run” will execute the program:
If an error occurs:
1
2
3
4
5
6
7
Exception: Request failed for https://firebaseappdistribution.googleapis.com returned code 403. Truncated server response: {
"error": {
"code": 403,
"message": "Request had insufficient authentication scopes.",
"status": "PERMISSION_DENIED",
"details":... (use muteHttpExceptions option to examine full response)
...
or
1
Exception: Specified permissions are not sufficient to call UrlFetchApp.fetch. Required permissions: https://www.googleapis.com/auth/script.external_request
Please confirm that the oauthScopes in appsscript.json
includes the following two configuration settings (refer to step 2):
1
2
3
4
"oauthScopes": [
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/cloud-platform"
]
If an error occurs:
1
2
3
4
Exception: Request failed for https://firebaseappdistribution.googleapis.com returned code 401. Truncated server response: {
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or othe... (use muteHttpExceptions option to examine full response)
This indicates that the bound GCP project has not been set up (refer to step 1) or that the GCP project has not enabled the desired Google APIs, or that the current account does not have permissions for that GCP / Google APIs or lacks permissions for that Firebase App. Please check the settings.
If an error occurs:
1
Exception: Request failed for https://firebaseappdistribution.googleapis.com returned code 404. Truncated server response:
or
1
2
3
4
5
6
7
Exception: Request failed for https://firebaseappdistribution.googleapis.com returned code 400. Truncated server response: {
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT"
}
}
Please confirm whether the Google APIs request path is correct.
Integration Successful 🎉🎉🎉
You can see that with less than 10 lines of code, you can seamlessly integrate with Google APIs, which is really convenient. Friends interested can take a look at the relatively cumbersome steps for exchanging authentication tokens when implementing it yourself for Google APIs integration.
Next Steps:
Combine with the previous article “Using Google Apps Script Web App Forms to Connect to GitHub Action CI/CD” to link CI/CD tasks, presenting the Firebase App Distribution download link directly on the Web App for colleagues to download conveniently.
Demo Result
Other Google APIs can also be integrated in a similar manner.
If you have any questions or suggestions, feel free to contact me.
This article was first published on Medium ➡️ Click Here
Automatically converted and synchronized using ZMediumToMarkdown and Medium-to-jekyll-starter.