How to use Google Sheets API with google service account on Node.js

You have to install googleapis package:

npm install googleapis

Save credentials for service account to the root derictory of the project under the name credentials.json

Grant access to your spreadsheet to service account.

Create index.js file and paste following code:

let {google} = require('googleapis');
let privatekey = require('./credentials.json');

const SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
async function getAuthToken() {
  const auth = new google.auth.GoogleAuth({
    keyFile:'./credentials.json',
    scopes: SCOPES
  });
  const authToken = await auth.getClient();
  return authToken;
}

const myId = 'YOUR SPREADSHEET ID';

const main = async () => {
  const auth = await getAuthToken()
  const client = google.sheets({ version: "v4", "auth": auth });
  const data = await client.spreadsheets.get({ spreadsheetId: myId});
  console.log(data.data)
}
main()

Run node index.js

Enjoy!

Our Visitor

0 0 0 7 2 0
Users Today : 0
Users Yesterday : 2
Users Last 7 days : 9
Users Last 30 days : 30
Users This Month : 15
Users This Year : 203
Total Users : 720
Views Today :
Views Yesterday : 2
Views Last 7 days : 49
Views Last 30 days : 82
Views This Month : 67
Views This Year : 330
Total views : 1087
Who's Online : 0
Your IP Address : 3.238.82.77
Server Time : 2024-10-14

Leave a Reply

Your email address will not be published. Required fields are marked *