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 serive 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!

Leave a Reply

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