I want to get access to my G-Suite account in a nodejs server, using Gmail API. I understood I should create Service Account and authenticate with its credentials. I tried many examples and ways but couldn't make it works.
This is the last try I've made. returns 400 bad request.
code: 400, errors: [ { domain: 'global', reason: 'failedPrecondition', message: 'Bad Request' } ]
const {GoogleAuth} = require('google-auth-library');
const credentials = require('./sevice-account-credentials.json');
async function main() {
const clientEmail = credentials.client_email;
const privateKey = credentials.private_key;
if (!clientEmail || !privateKey) {
throw new Error(`
The CLIENT_EMAIL and PRIVATE_KEY environment variables are required for
this sample.
`);
}
const auth = new GoogleAuth({
credentials: {
client_email: clientEmail,
private_key: privateKey,
},
scopes: 'https://mail.google.com/',
});
const client = await auth.getClient();
const projectId = await auth.getProjectId();
const url = `https://www.googleapis.com/gmail/v1/users/[email protected]/labels/label_id`;
const res = await client.request({url});
console.log(res.data);
}
main().catch(console.error);