Go クイックスタート

Google Apps Script API にリクエストを行う Go コマンドライン アプリケーションを作成します。

クイックスタートでは、Google Workspace API を呼び出すアプリを設定して実行する方法について説明します。このクイックスタートでは、テスト環境に適した簡略化された認証方法を使用します。本番環境では、アプリに適したアクセス認証情報を選択する前に、 認証と認可 について学習することをおすすめします。

このクイックスタートでは、Google Workspace の推奨 API クライアント ライブラリを使用して、認証と認可フローの詳細を処理します。

目標

  • 環境をセットアップする。
  • サンプルをセットアップする。
  • サンプルを実行する。

前提条件

  • Google ドライブが有効になっている Google アカウント。

環境をセットアップする

このクイックスタートを完了するには、環境をセットアップします。

API を有効にする

Google API を使用する前に、Google Cloud プロジェクトで API を有効にする必要があります。1 つの Google Cloud プロジェクトで 1 つ以上の API を有効にできます。

このクイックスタートを完了するために新しい Google Cloud プロジェクトを使用する場合は、OAuth 同意画面を構成します。Cloud プロジェクトでこの手順をすでに完了している場合は、次のセクションに進んでください。

  1. Google API Console で、メニュー アイコン > [Google Auth Platform] > [ブランディング] に移動します。

    [ブランディング] に移動

  2. Google Auth Platform をすでに構成している場合は、[ブランディング]、[対象]、[データアクセス] で次の OAuth 同意画面の設定を構成できます。[**Google Auth Platform はまだ構成されていません**] というメッセージが表示されたら、[**スタートガイド**] をクリックします。
    1. [アプリ情報] の [アプリ名] に、アプリの名前を入力します。
    2. [**ユーザー サポートメール**] で、ユーザーが同意について問い合わせる際に使用するサポートのメールアドレスを選択します。
    3. [続行] をクリックします。
    4. [対象] で [内部] を選択します。
    5. [続行] をクリックします。
    6. [連絡先情報] で、プロジェクトに対する変更の通知を受け取る [メールアドレス] を入力します。
    7. [続行] をクリックします。
    8. [完了] で、Google API サービスのユーザーデータに関するポリシーを確認し、同意する場合は [Google API サービス: ユーザーデータに関するポリシーに同意します] を選択します。
    9. [続行] をクリックします。
    10. [作成] をクリックします。
  3. 現時点では、スコープの追加はスキップできます。 今後、 Google Workspace 組織外で使用するアプリを作成する場合は、[ユーザータイプ] を [外部] に変更する必要があります。次に、アプリに必要な認可スコープを追加します。詳細については、完全な OAuth 同意画面を構成するガイドをご覧ください。

デスクトップ アプリケーションの認証情報を認可する

エンドユーザーを認証してアプリ内のユーザーデータにアクセスするには、1 つ以上の OAuth 2.0 クライアント ID を作成する必要があります。クライアント ID は、Google の OAuth サーバーで個々のアプリを識別するために使用します。アプリが複数のプラットフォームで実行される場合は、プラットフォームごとに個別のクライアント ID を作成する必要があります。
  1. Google API Console で、メニュー アイコン > [Google Auth Platform] > [クライアント] に移動します。

    [クライアント] に移動

  2. [クライアントの作成] をクリックします。
  3. [アプリケーション タイプ] [>] [デスクトップ アプリ] をクリックします。
  4. [名前] フィールドに、認証情報の名前を入力します。この名前は Google API Console にのみ表示されます。
  5. [作成] をクリックします。

    新しく作成した認証情報が [OAuth 2.0 クライアント ID] に表示されます。

  6. ダウンロードした JSON ファイルを credentials.json として保存し、 ファイルを作業ディレクトリに移動します。

職場環境を整える

  1. 作業ディレクトリを作成します。

    mkdir quickstart
    
  2. 作業ディレクトリを変更します。

    cd quickstart
    
  3. 新しいモジュールを初期化します。

    go mod init quickstart
    
  4. Google Apps Script API Go クライアント ライブラリと OAuth2.0 パッケージを取得します。

    go get google.golang.org/api/script/v1
    go get golang.org/x/oauth2/google
    

サンプルをセットアップする

  1. 作業ディレクトリに quickstart.go という名前のファイルを作成します。

  2. ファイルに次のコードを貼り付けます。

    apps_script/quickstart/quickstart.go
    package main
    
    import (
    	"context"
    	"encoding/json"
    	"fmt"
    	"log"
    	"net/http"
    	"os"
    
    	"golang.org/x/oauth2"
    	"golang.org/x/oauth2/google"
    	"google.golang.org/api/option"
    	"google.golang.org/api/script/v1"
    )
    
    // Retrieve a token, saves the token, then returns the generated client.
    func getClient(config *oauth2.Config) *http.Client {
    	// The file token.json stores the user's access and refresh tokens, and is
    	// created automatically when the authorization flow completes for the first
    	// time.
    	tokFile := "token.json"
    	tok, err := tokenFromFile(tokFile)
    	if err != nil {
    		tok = getTokenFromWeb(config)
    		saveToken(tokFile, tok)
    	}
    	return config.Client(context.Background(), tok)
    }
    
    // Request a token from the web, then returns the retrieved token.
    func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
    	authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
    	fmt.Printf("Go to the following link in your browser then type the "+
    		"authorization code: \n%v\n", authURL)
    
    	var authCode string
    	if _, err := fmt.Scan(&authCode); err != nil {
    		log.Fatalf("Unable to read authorization code: %v", err)
    	}
    
    	tok, err := config.Exchange(context.TODO(), authCode)
    	if err != nil {
    		log.Fatalf("Unable to retrieve token from web: %v", err)
    	}
    	return tok
    }
    
    // Retrieves a token from a local file.
    func tokenFromFile(file string) (*oauth2.Token, error) {
    	f, err := os.Open(file)
    	if err != nil {
    		return nil, err
    	}
    	defer f.Close()
    	tok := &oauth2.Token{}
    	err = json.NewDecoder(f).Decode(tok)
    	return tok, err
    }
    
    // Saves a token to a file path.
    func saveToken(path string, token *oauth2.Token) {
    	fmt.Printf("Saving credential file to: %s\n", path)
    	f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
    	if err != nil {
    		log.Fatalf("Unable to cache oauth token: %v", err)
    	}
    	defer f.Close()
    	json.NewEncoder(f).Encode(token)
    }
    
    func main() {
    	ctx := context.Background()
    	b, err := os.ReadFile("credentials.json")
    	if err != nil {
    		log.Fatalf("Unable to read client secret file: %v", err)
    	}
    
    	// If modifying these scopes, delete your previously saved token.json.
    	config, err := google.ConfigFromJSON(b, "https://www.googleapis.com/auth/script.projects")
    	if err != nil {
    		log.Fatalf("Unable to parse client secret file to config: %v", err)
    	}
    	client := getClient(config)
    
    	srv, err := script.NewService(ctx, option.WithHTTPClient(client))
    	if err != nil {
    		log.Fatalf("Unable to retrieve Script client: %v", err)
    	}
    
    	req := script.CreateProjectRequest{Title: "My Script"}
    	createRes, err := srv.Projects.Create(&req).Do()
    	if err != nil {
    		// The API encountered a problem.
    		log.Fatalf("The API returned an error: %v", err)
    	}
    	content := &script.Content{
    		ScriptId: createRes.ScriptId,
    		Files: []*script.File{{
    			Name:   "hello",
    			Type:   "SERVER_JS",
    			Source: "function helloWorld() {\n  console.log('Hello, world!');}",
    		}, {
    			Name: "appsscript",
    			Type: "JSON",
    			Source: "{\"timeZone\":\"America/New_York\",\"exceptionLogging\":" +
    				"\"CLOUD\"}",
    		}},
    	}
    	updateContentRes, err := srv.Projects.UpdateContent(createRes.ScriptId,
    		content).Do()
    	if err != nil {
    		// The API encountered a problem.
    		log.Fatalf("The API returned an error: %v", err)
    	}
    	log.Printf("https://script.google.com/d/%v/edit", updateContentRes.ScriptId)
    }

サンプルを実行する

  1. 作業ディレクトリで、サンプルをビルドして実行します。

    go run quickstart.go
    
  1. サンプルを初めて実行すると、アクセス権の承認を求めるメッセージが表示されます。
    1. Google アカウントにまだログインしていない場合は、ログインを求められたらログインします。複数のアカウントにログインしている場合は、承認に使用するアカウントを 1 つ選択します。
    2. [Accept] をクリックします。

    Go アプリケーションが実行され、Google Apps Script API が呼び出されます。

    認可情報はファイル システムに保存されるため、次回サンプル コードを実行するときに認可を求められることはありません。

次のステップ