結論
Google Sheets API だけじゃなくて、Google Drive API も使う
const sheets = google.sheets({ version: "v4", auth: oAuth2Client }); const drive = google.drive({ version: "v3", auth: oAuth2Client }); // スプレッドシートを作成する const createdSheet = await sheets.spreadsheets.create(); // Google Drive APIでスプレッドシートの権限を作成する await drive.permissions.create({ fileId: createdSheet.data.spreadsheetId, requestBody: { type: "anyone", role: "writer", }, }); // 誰でも編集できるスプレッドシートのURL console.log(createdSheet.data.spreadsheetUrl);
動くサンプル
credential.jsonとtoken.jsonはあらかじめ作成してある前提です。
トークンの生成がまだの方はこちらのドキュメントを参考に、クレデンシャルのダウンロードとトークンの生成を行ってください。
https://developers.google.com/sheets/api/quickstart/nodejs
import { promises as fs } from "fs"; import { google } from "googleapis"; (async () => { const credentials: GCPCredentials = await fs .readFile(`${__dirname}/../credentials.json`) .then((b) => b.toString()) .then((s) => JSON.parse(s)); const { client_id, client_secret, redirect_uris } = credentials.installed; const oAuth2Client = new google.auth.OAuth2( client_id, client_secret, redirect_uris[0] ); const token = await fs .readFile(`${__dirname}/../token.json`) .then((b) => b.toString()) .then((s) => JSON.parse(s)); oAuth2Client.setCredentials(token); const sheets = google.sheets({ version: "v4", auth: oAuth2Client }); const drive = google.drive({ version: "v3", auth: oAuth2Client }); const createdSheet = await sheets.spreadsheets.create(); await drive.permissions.create({ fileId: createdSheet.data.spreadsheetId, requestBody: { type: "anyone", role: "writer", }, }); console.log(createdSheet.data.spreadsheetUrl); })(); type GCPCredentials = { installed: { client_id: string; project_id: string; auth_uri: string; token_uri: string; auth_provider_x509_cert_url: string; client_secret: string; redirect_uris: string[]; }; };
元記事はこちら
https://qiita.com/Michinosuke/items/b6eb04a9882aae67fb2a
著者:
@Michinosuke
アイレットなら、Google Cloud で稼働するサーバーを対象とした監視・運用・保守における煩わしい作業すべてを一括して対応し、経験豊富なプロフェッショナルが最適なシステム環境を実現いたします。Google Cloud プレミアサービスパートナーであるアイレットに、ぜひお任せください。
Google Cloud サーバー監視・運用サービスページ:
https://cloudpack.jp/service/gcp/maintenance.html
その他のサービスについてのお問合せ、お見積り依頼は下記フォームよりお気軽にご相談ください。
https://cloudpack.jp/contact/form/