简体   繁体   中英

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});

  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM