Jonny Piazzi
Jonny Piazzi

Reputation: 3784

First step on Google API + GMAIL = bad request

I'm very new on Google API, Eventually I want to send emails using it. But for now I'm trying something a little bit simpler (and then build it up).

List all emails in the inbox.

From Gmail > API > Reference, I followed these steps:

On Google API Console:

  1. Created my application.
  2. Under API & Services > Credentials I created a user with Project/Owner role (just to make sure there is no permission problems in this step).
  3. Then I created a key and download the json file.
  4. At API & Services > Library I enabled Gmail.

And using the Reference I put together this snippet:

app.ts

import { google } from 'googleapis';
import credentials from './credentials';

async function main() {
  const auth = new google.auth.GoogleAuth({
    credentials,
    scopes: [
      'https://mail.google.com/',
      'https://www.googleapis.com/auth/gmail.compose',
      'https://www.googleapis.com/auth/gmail.modify',
      'https://www.googleapis.com/auth/gmail.readonly',
      'https://www.googleapis.com/auth/gmail.metadata'
    ]
  });

  const authClient = await auth.getClient();

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

  const data = await gmail.users.messages.list({ userId: 'me' });

  console.log(data);
}

main().catch(console.log);

package.json

...

"dependencies": {
  googleapis": "^48.0.0"
}

...

Every time I ran this snippet I got:

[01] GaxiosError: Bad Request
[02] at Gaxios._request (~\node_modules\gaxios\build\src\gaxios.js:85:23)
...
[06] response: {
...
[35] status: 400,
[36] statusText: 'Bad Request',
[37] request: {
[38] responseURL: 'https://www.googleapis.com/gmail/v1/users/me/messages'
...

I tried many diferent configurations on Google API Console. Tried to change the scope (list of urls from line 8 to 12) for many others, change the credentials.json to a .js and .ts format, put in a global variable (GOOGLE_APPLICATION_CREDENTIALS) instead of a direct import. But despite of all my attempts, I got aways the same error.

How can I fix that?

Upvotes: 0

Views: 623

Answers (1)

Piyush Singh
Piyush Singh

Reputation: 2962

Check out example from here which does exactly what you want. They seem use a sampleclient instead of a credentials library.

Upvotes: 0

Related Questions