LoginSignup
0
0

More than 1 year has passed since last update.

サービスアカウントでspreadsheet-apiへアクセスする(java)

Last updated at Posted at 2022-06-20

概要

ネット上ではいろんなサンプルコードがあったが、javaバージョンは少なかったので、個人メモ用で、
gcpのサービスアカウントを使って、spreadsheetのデータを取得する方法について、記載する。

step1: gcp上でサービスアカウントを作成し、サービスのキーを作成する

スクリーンショット 2022-06-21 0.50.04.png

  • キーを記載しているjsonファイルをダウンロードする
  • 単純に、spreadsheetのデータを取る場合、ロールなど付与しなくても良い。詳細の理由

step2: 実装

// scoreを定義する
final List<String> scopes = List.of("https://docs.google.com/feeds", "https://spreadsheets.google.com/feeds");
final GsonFactory factory = new GsonFactory();
final String applicationName = "{任意}";
// スプレッドシートのID
finak String spreadId = "id";
// step1 作成したキーを記載しているファイルをロードする
final InputStream in = new FileInputStream("{key_file_path.json}");
// adapterを作成する
final HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(GoogleCredentials.fromStream(in).createScoped(scopes));
final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
final Sheets sheetClient = new Sheets.Builder(httpTransport, , adapter)
                .setApplicationName(applicationName)
                .build();

//シートのリストを取得する
final List<Sheet> sheets = sheetClient.spreadsheets().get(spreadId).execute().getSheets();

//1個目のシート名を取得する
final String sheetName = sheets.get(0).getProperties().getTitle();

//↑によって、1個目のシートのデータを取得する
final List<List<Object>> csvRecords = sheets.spreadsheets().values().get(spreadId, sheetName).execute().getValues();

スプレッドシートのIDを確認する方法: (https://developers.google.com/sheets/api/guides/concepts)

step 3

アクセスしたいシートを開き、step1で作成したサービスアカウントのメールアドレスに共有する

参考

感想

I think this is confusing and poorly explained in Google's documentation but IAM and OAuth scopes are mostly (now) complementary technologies.
I consider IAM to refine or provide more granular, account|credential-specific scopes

↑と同じ感じで、gcpは認証周りのドキュメントは分かりにくいなと思いました。

以上

0
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
0
0