LoginSignup
1
0

More than 1 year has passed since last update.

【Google Sheets API v4】OAuth Client ID を使ったセットアップ(token.jsonの生成まで)

Last updated at Posted at 2022-08-31

Google Sheets API v4を使うために認証情報を取得する必要があるが、その方法は3種類ある。

API KEY はpublicのスプレッドシートを扱う時に使うよう。
今回はチームで管理するスプレッドシートを扱うのでServiceAccountかOAuthClientIdがよさそう。

ServiceAccountの方が必要な設定はラクだけどServiceAccountを作った時に1回だけダウンロードできる秘密鍵を管理する必要があるので、公式のquick start通り、OAuthClientIdを使う。

やること

  1. credentialの取得
    quick start のprerequisitesまでやる。
    OAuthClientIdでcredenctialを作成する時は「デスクトップ アプリ」を選択。
  2. token.jsonの取得
    1. プロジェクトディレクトリを作成
    2. 以下を実行
      npm init -y
      npm install googleapis@105 @google-cloud/local-auth@2.1.0 --save
      
    3. index.jsを作成してsample codeをcopy。
    4. index.jsのSCOPESを目的の権限に変更。(今回はスプレッドシートの読み書きをしたいのでhttps://www.googleapis.com/auth/spreadsheetsに変更)
    5. 1.でダウンロードしたものをcredencials.jsonにrenameしてrootに配置
    6. index.jsを実行
      node index
      
    7. token.jsonが生成される。

まとめ

今回のプロジェクトはこちら(github)
読み書きのサンプルコードも軽く載せてます。

// spreadsheet.js

const fs = require('fs').promises;
const path = require('path');
const process = require('process');
const {google} = require('googleapis');
const dotenv = require('dotenv');
dotenv.config();

const TOKEN_PATH = path.join(process.cwd(), 'token.json');

const authorize = async ()  => {
  const content = await fs.readFile(TOKEN_PATH);
  const credentials = JSON.parse(content);
  return google.auth.fromJSON(credentials);
};

authorize().then(async (auth) => {

  // 読み取り
  const sheets = google.sheets({version: 'v4', auth});
  const read = await sheets.spreadsheets.values.get({
    spreadsheetId: process.env.GOOGLE_SHEET_API_SPREADSHEET_ID,
    range: process.env.GOOGLE_SHEET_API_TEST_SHEET,
  });
  const rows = read.data.values;
  console.log(rows);

  // 更新
  rows.push(['update'])
  const update = await sheets.spreadsheets.values.update({
    spreadsheetId: process.env.GOOGLE_SHEET_API_SPREADSHEET_ID,
    range: process.env.GOOGLE_SHEET_API_TEST_SHEET,
    valueInputOption: 'RAW', // RAW/USER_ENTERED
    includeValuesInResponse: true,
    resource : {
      values : rows,
    }
  });
  // resource.valueの値
  console.log(update.data.updatedData.values);

  // 挿入
  const append = await sheets.spreadsheets.values.append({
    spreadsheetId: process.env.GOOGLE_SHEET_API_SPREADSHEET_ID,
    range: process.env.GOOGLE_SHEET_API_TEST_SHEET,
    valueInputOption: 'RAW',
    insertDataOption: 'INSERT_ROWS', // INSERT_ROWS/OVERWRITE
    includeValuesInResponse: true,
    resource : {
      values : [
        ['append']
      ],
    }
  });
  // resource.valueの値
  console.log(append.data.updates.updatedData.values);

}).catch(console.error);
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0