0

Using a service account file to access google sheet is working as expected

import { google } from 'googleapis';
import serviceAccount from 'serviceKey.json';

const spreadsheetId = 'spreadsheet-id';
const sheets = google.sheets({ version: 'v4' });

const jwtClient = new google.auth.JWT({
  email: serviceAccount.client_email,
  key: serviceAccount.private_key,
  scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});

const appendValue = async () => {
    await jwtClient.authorize();
    await sheets.spreadsheets.values.append({
      auth: jwtClient,
      spreadsheetId,
      range: 'Test!A2:E2',
      valueInputOption: 'RAW',
      requestBody: { values: [['A', 'B', 'C', 'D', 'E']] },
    });
};

But trying it using default application credentials throws an error saying Login is Required.

export GOOGLE_APPLICATION_CREDENTIALS="/path/to/serviceKey.json"
import { google } from 'googleapis';

const spreadsheetId = 'spreadsheet-id';
const sheets = google.sheets({ version: 'v4' });

const appendValue = async () => {
    await sheets.spreadsheets.values.append({
      spreadsheetId,
      range: 'Test!A2:E2',
      valueInputOption: 'RAW',
      requestBody: { values: [['A', 'B', 'C', 'D', 'E']] },
    });
};
Naresh
  • 941
  • 9
  • 22
  • What is `default application credentials`? – Tanaike Feb 08 '22 at 11:49
  • Can you print the env var `GOOGLE_APPLICATION_CREDENTIALS` in your python code to check if it is taken into account? – guillaume blaquiere Feb 08 '22 at 12:05
  • @Tanaike https://cloud.google.com/docs/authentication/production#automatically – Naresh Feb 10 '22 at 12:38
  • @guillaumeblaquiere I can access calendar API after setting `GOOGLE_APPLICATION_CREDENTIALS` its just not working with sheets – Naresh Feb 10 '22 at 12:45
  • Were you able to try using `authClient`? @Naresh – Catherine O Feb 21 '22 at 12:29
  • I'm facing this right now. Did you ever solve this? I ended up on this page https://cloud.google.com/docs/authentication/provide-credentials-adc#attached-sa which shows installing a CLI first, going thru a web page auth with a google account, then things appeared further set up. However, I am now facing the same login required issue even after this. – rom Dec 11 '22 at 20:11
  • No. As i mentioned in the question, I ended up using `serviceKey.json` file to authenticate. – Naresh Dec 13 '22 at 06:27

0 Answers0