google-auth-token-generator

Gooogle系APIのtoken.jsonを取得するためのCLIツールです。 npx経由で実行すればインストール不要です。

Usage no npm install needed!

<script type="module">
  import googleAuthTokenGenerator from 'https://cdn.skypack.dev/google-auth-token-generator';
</script>

README

Image from Gyazo

google-auth-token-generator

Gooogle系APIのtoken.jsonを取得するためのCLIツールです。 npx経由で実行すればインストール不要です。

  • Google Drive
  • Gmail
  • Google Calender
  • Youtube Data API
  • Google Sheets

に対応しています。(2021/5/3時点)

使い方

    1. CLIツールとして、token.jsonの生成が出来ます。
    1. oAuthClientの生成関数のモジュールとして利用できます。

1. token.jsonの生成

    1. Googleのサイトから利用したいAPIのcredentials.jsonを取得します。
    1. npx google-auth-token-generatorを実行します。
    1. token.jsonが生成されます

2. oAuthClientの生成モジュール

読み込みます。googleapisも追加でインストールしましょう。

const {google} = require('googleapis');
const {oAuth2ClientGen} = require('google-auth-token-generator');

利用する際は以下のように読み込みます。 ファイル名は任意に変更できますがcredentials.jsonとtoken.jsonがデフォルトです。

const auth = oAuth2ClientGen({
  library: google,
  /*ファイル利用の場合*/
  CREDENTIALS_PATH: `credentials.json`, // optional
  TOKEN_PATH: 'token.json'; // optional
});

また、環境変数などを利用したい場合はCREDENTIALSとTOKENのキーにセットして下さい。ファイル読み込みはしません。

const auth = oAuth2ClientGen({
  library: google,
  /*環境変数利用の場合*/
  CREDENTIALS: process.env.GOOGLE_CREDENTIAL, //optional
  TOKEN: process.env.GOOGLE_TOKEN,  //optional
});

Google Spread SheetsのAPI利用サンプル

'use strict';

const {google} = require('googleapis');
const {oAuth2ClientGen} = require('google-auth-token-generator');

(async () => {
    const auth = oAuth2ClientGen({library: google});
    const sheets = google.sheets({version: 'v4', auth});

    try {
        const res = await sheets.spreadsheets.values.get({
            spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
            range: 'Class Data!A2:E',
        });

        const rows = res.data.values;
        if (rows.length) {
          console.log('Name, Major:');
          // Print columns A and E, which correspond to indices 0 and 4.
          rows.map((row) => {
            console.log(`${row[0]}, ${row[4]}`);
          });
        } else {
          console.log('No data found.');
        }

    } catch (error) {
        console.log('The API returned an error: ' + error);
    }
})();

how to use

    1. Get credentials.json first from the Google API site.
    1. run npx google-auth-token-generator
    1. A token.json file will be generated.