DEV Community

Write to Google Sheets from a local script via gcloud CLI authentication

The author needed to pull data from the GitHub API and publish it to a Google Sheet to share charts about code review workload. They wrote a Node.js script to accomplish this task, initially generating ad hoc CSV data that was manually copied into Google Sheets. To automate the process, the author used the Google Sheets API, which required authentication. The author found that authentication was the most challenging part of the process, taking around four hours to set up. They discovered that the gcloud CLI's setup of application default credentials can operate as an OAuth proxy for Google Workspace code, expanding authentication to include additional permissions. To set up authentication, the author enabled the Sheets API in their Cloud project and set their application default credentials using the gcloud CLI, claiming non-default OAuth scopes. This triggered an OAuth flow that granted the credential read/write access to all Google Sheets data. The author then initialized a Node client for Google Sheets using the googleapis library and created a function to append data to a sheet. They made changes to the sample code from the docs to enable easier reuse of the client and parameterize the request. The author's code appends data to the sheet using the client initialization code and handles errors by logging them to the console. They use the "append" method to add new rows without removing earlier rows, as their script collects monthly metrics. The author provides an example of how to call the appendDataToSheet function and notes that the Sheets API has some good tips, such as not sending more than one API request per second per sheet. They also mention that they might switch to using Cloud Scheduler and Cloud Run Jobs if they productionize the script.
favicon
dev.to
dev.to
Create attached notes ...