question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Gmail API with service account- Precondition check failed

See original GitHub issue

I’m trying to connect with the google API’s for the first time, and when I attempt to make a request to the gmail API I’m getting a Precondition check failed error. I am using a service account authorization, not Oauth2 user consent. Things I’ve tried:

  1. Authorized “domain wide delegation” for the service account.
  2. Ensured the APP is trusted in the G suite account.
  3. Have also tried just returning the projectId from the API - and that works. So it is authorizing and connecting. It’s when I try to make a request to gmail specifically that’s giving me issue.
  4. Service account role is “owner”

This is adapted from a sample, but the sample did not use service account auth so I wasn’t able to use the sample directly.

const path = require('path');
const {google} = require('googleapis');

const gmail = google.gmail('v1');

async function runSample() {
  // Obtain user credentials to use for the request
  const auth = new google.auth.GoogleAuth({
    keyFile: path.resolve(__dirname, 'google-key.json'),
    scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
  });
  google.options({auth});

  const res = await gmail.users.messages.list({userId: 'me'}); // have tried with my gsuite email address as well
  console.log(res.data);
  return res.data;
}

if (module === require.main) {
  runSample().catch(console.error);
}
module.exports = runSample;

returning Error: Precondition check failed.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:16
  • Comments:11 (2 by maintainers)

github_iconTop GitHub Comments

17reactions
vettloffahcommented, Aug 9, 2020

I figured out how to solve the issue.

I would like to sbumit a pull request for this issue to add a sample to the gmail sample library. It would look something like this (can work on refactoring to match code style in other samples if you give me the go-ahead on submitting a PR):

const path = require('path');
const {google} = require('googleapis');

async getMessageList(userId, qty) {

  const JWT = google.auth.JWT;
  const authClient = new JWT({
    keyFile: path.resolve(__dirname, 'google-key.json'),
    scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
    subject: 'admin@example.com' // google admin email address to impersonate
  });

  await authClient.authorize(); // once authorized, can do whatever you want

  const gmail = google.gmail({
    auth: authClient,
    version: 'v1'
  });

  const response = await gmail.users.messages.list({
    includeSpamTrash: false,
    maxResults: qty,
    q: "",
    userId: userId
  });

  // the data object includes a "messages" array of message data
  return response.data;

}
10reactions
sqrrrlcommented, Sep 15, 2020

The Gmail API isn’t intended to be used with service accounts (other than domain-wide delegation use cases.) You need to be acting as a real user – either using oauth credentials obtained with user consent, or in the case of a Gsuite domain, using a service account delegating/impersonating a real user.

I’ll file a bug to make the error message clearer, but it’s likely that the failed precondition is that the service account isn’t a valid gmail user.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Gmail REST API : 400 Bad Request + Failed Precondition
Gmail REST API : 400 Bad Request + Failed Precondition · Second Step : Create the Gmail Service based on the credentials: Gmail...
Read more >
Precondition check failed error using Gmail API v1 | Digital ...
My understanding is following: 1. you need to have G Suite account activated (if you don't have it you can activate it for...
Read more >
Send a mail with a service account using Gmail API
Send a mail with a service account using Gmail API. 1486 views ... googleapi: Error 400: Precondition check failed., failedPrecondition.
Read more >
error: code: 400 – Precondition check failed - WordPress.org
Hi, I am trying to solve this problem I have configured the Gmail API correctly of my account. It was working from previously...
Read more >
Resolve errors | Gmail - Google Developers
To fix this error, refresh the access token using the long-lived refresh token. If you are using a client library, it automatically handles...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found