4
0

More than 3 years have passed since last update.

Java/Google Sheets API V4/APIキー認証の場合はデータの更新処理(update)は401エラー(OAuth認証が必要)さらにSheetsオブジェクトにcredentialを渡すインタフェースが無い

Last updated at Posted at 2020-06-06

できないならできないと書いておいて欲しい。=>Googleさん

環境

項目 バージョン等
java 1.8
Sheets API Version 4
スプレッドシートの所有状態 所有かつURLを知っていれば誰でも編集可能

症状

  • スプレットシートを所有しているアカウントでGoogle API Projectを作成
  • Sheets APIを有効可
  • APIキーを作成(Sheet API使用を割り当て)
  • APIキーを使ってスプレッドシートにアクセス
    • 読み込み(get)はOK
    • 書き込み(update)で401エラー
      • 例外はGoogleJsonResponseException
      • エラーメッセージ:401 Unauthorized

原因

(どこにも書いてないが)書き込みの場合は、APIキー認証では不可でOAuth2認証が必要な模様。

どこにも書いてないのに、この結論を得られたのはAPI Explorerのおかげ。
ブラウザからAPIリクエストを実行できるよくある機能ですが、リクエストパラメタ設定だけでなく、認証方法も選択して実行できます。
その結果、API Key認証だと401エラー。OAuth2認証だと成功しました。

API Explorerはこちら。

Request設定 利用する認証設定
Image from Gyazo Image from Gyazo

参考

失敗レスポンス

{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

参考/成功レスポンス

{
  "spreadsheetId": "1aAk_HFTmn*********************************",
  "updatedRange": "'p01'!B3:M3",
  "updatedRows": 1,
  "updatedColumns": 12,
  "updatedCells": 12
}

[悲報]Sheets APIのJavaライブラリではSheetsインスタンスにOAuth2の認証情報を渡す方法がわからない

QuickStartのサンプルコードだと、Sheets.Builderコンストラクターの第三引数でcredentialを渡せるようになっているのですが、実際はhttpInitializerになっていて、渡せません(コンパイルエラー)。

bigQueryのようにbuilder()後にsetしたりできるのかと散々探しましたが、ダメ。Sheetsインスタンスの作成は全てのサンプルが存在しないコンストラクタになっています。Googleさん、勘弁してよ…。

**
java
BigQuery bigquery =
BigQueryOptions.newBuilder()
★.setCredentials(credentials)★
.setProjectId(projectId)
.build()
.getService();

httpInitializerのHttpRequestにSetOAuthTokenというインタフェースがあるので、これを使うのかな?

もうJavaじゃなくていいや。

サンプルコード

Sheets service = 
       new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
           .setApplicationName(APPLICATION_NAME)
           .build();

実際/公式APIドキュメントより

Builder(
  com.google.api.client.http.HttpTransport transport, 
  com.google.api.client.json.JsonFactory jsonFactory, 
  com.google.api.client.http.HttpRequestInitializer httpRequestInitializer)

4
0
1

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