Google Sheets Api Authorization with a service account

I am using googleapis library v44.0.0. When I try to log in, I get an error.

Google Sheets API has not been used in project 33120758 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/sheets.googleapis.com/overview?project=33120758 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.

I use google-auth-library version ^ 0.10.0 on the same project. And this error was not.

const { google } = require("googleapis");
// ...
const JwtClient = new google.auth.JWT(
  client_email, 
  null, 
  private_key, 
  ["https://www.googleapis.com/auth/spreadsheets"]
);
await JwtClient.authorize();
google.options({ auth: JwtClient });

// ...
const client = google.sheets({ version: "v4" });
const data = await client.spreadsheets.get({ spreadsheetId: myId});

Upvotes: 5

Views: 3595

Answers (1)

Tanaike
Tanaike

Reputation: 201378

  • You want to use Sheets API with the service account.
  • You want to achieve this using googleapis with Node.js.

If my understanding is correct, how about this modification?

Modified script:

From:
await JwtClient.authorize();
google.options({ auth: JwtClient });

// ...
const client = google.sheets({ version: "v4" });
const data = await client.spreadsheets.get({ spreadsheetId: myId});
To:
const client = google.sheets({ version: "v4", "auth": JwtClient });
const data = await client.spreadsheets.get({ spreadsheetId: myId});
console.log(data.data)

Note:

  • If you want to retrieve the data from the Spreadsheet on your own Google Drive, please share the Spreadsheet with the email of the service account. By this, the Spreadsheet can be retrieved from the service account. Please be careful this.

In my environment, I could confirm that the modified script worked. But if this didn't resolve your issue, I apologize.

Upvotes: 5

Related Questions