To access the Sheets API, you will need to enable the Sheets API, obtain credentials, and grant access to your Sheet.
Based on these instructions
- Open the Google Developers Console
- Select your project or create a new one (and then select it)
- Enable the Sheets API for your project
- In the sidebar on the left, select
APIs & Services > Library
- Search for "sheets", Click on
Google Sheets API
- Click
Enable
- In the sidebar on the left, select
- In the sidebar on the left, select
APIs & Services > Credentials
- Click on
Create Credentials > Service Account
- Enter name, description, click
Create
- Skip permissions and roles
- Click
Create Key > JSON > Create
- JSON key will be downloaded to your computer
- The JSON file contains your
GOOGLE_SERVICE_ACCOUNT_EMAIL
andPRIVATE_KEY
- Open your Google Sheet in your browser
- Copy the Spreadsheet ID from the url for later use:
https://docs.google.com/spreadsheets/d/<spreadsheetId>/edit
- Click
Share
- Paste in the
GOOGLE_SERVICE_ACCOUNT_EMAIL
from the json file. ClickShare
You're all set!
The service account email address, cannot actually receive emails, so you may receive a "Delivery Status Notification - Failure" email when the invite message hard bounces off the account. That's normal, ignore it.
While you can use the Google Sheets SDK package, the (google-spreadsheet) is much easier to use (and has better docs!), so we'll use that:
npm i google-spreadsheet
Expose your GOOGLE_SERVICE_ACCOUNT_EMAIL
andGOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY
as environment variables in your code.
When using environment variables, the private key newlines will have to be unescaped using this regex: `GOOGLE_PRIVATE_KEY.replace(/\n/g, "\n")
const { GoogleSpreadsheet } = require('google-spreadsheet');
// Or embed it directly
async function main() {
const doc = new GoogleSpreadsheet(process.env.GOOGLE_SHEETS_DOCUMENT_ID);
await doc.useServiceAccountAuth({
client_email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
private_key: process.env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, "\n")
await doc.loadInfo();
console.log(doc.title)
});
}
main();
this code is outdated
but it is very helpful, and Bing AI can update the outdated parts.