Google Spreadsheet API v4 to “add a row” in spreadsheet using an “ApiKey”

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-07 09:48:59

问题


I am trying to use Google Spreadsheet API v4 to "add a row" in spreadsheet using an "ApiKey" directly without using an OAuth 2.0.

If I am using OAuth 2.0 its successfully "adding a row" but my requirement is to use "ApiKey"

Referred this URL: https://developers.google.com/sheets/api/guides/migration#add_a_new_row_of_data

But there is no proper document for using "APIKey ". When I tried using "Apikey" it is throwing me an error of "Unauthorized (401)".


回答1:


While the documentation isn't entirely clear, it is possible to add rows to a spreadsheet without needing to go through the OAuth flow where the app has to obtain consent from a specific user.

The flow, when using a service account, is very similar to the flow when using an APIKey, except a service account can be given explicit authorization to write to the sheet.

This works because a service account is like a user, just one that is not human. The process is as follows:

  • Go to the Google Cloud Console and create a service account in your GCP project. (If you don't have a project, you may need to create one.)
  • Create a key and download it as a JSON file. The JSON file will contain a private key, a key id, an email address for the service account, and other information. Keep this in a safe place. It's sensitive data.
  • Next, in your spreadsheet, add the service account email address as a user with edit access.

Afterwards, you can now use the service account client_email and the private_key from the JSON file in order to create a JWT token to authorize the request. You can now write to the sheet, since the service account is an authorized editor in the sheet.

See Using OAuth 2.0 to Access Google APIs - Service Accounts for more information. Note that although the documentation makes it sound like the service account can't access user data, it can in this case since we add the service account as an editor on the sheet.

Also, see Using OAuth 2.0 for Server to Server Applications.

Now, I will say that your question states that you "require using an APIKey". Instead, I'm assuming that your requirement is that the app must be able to write to the sheet without prompting users for authentication. If that's the case, then this solves your problem, but if the question really involves using an APIKey, then the only way to do that is to make the sheet publicly writeable to all unauthenticated users.

I also don't know what programming language you're using, so I'll leave the creation of a JWT token as an exercise for the reader, and the linked documentation also describes the process in Java, Python, and as a raw HTTP/REST request. Hope this helps!



来源:https://stackoverflow.com/questions/48144833/google-spreadsheet-api-v4-to-add-a-row-in-spreadsheet-using-an-apikey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!