美文网首页
如何使用 Google API

如何使用 Google API

作者: 狄仁杰666 | 来源:发表于2022-04-07 19:28 被阅读0次

前言

来啦老铁!

由于工作上有所接触,今天我们来学点工具相关的,他就是:

  • 如何使用 Google API

学习路径

  1. 创建 Google 项目;
  2. 启用 Google API 与服务;
  3. 创建凭据;
  4. 下载凭据
  5. 演示如何使用 Google API;

1. 创建 Google 项目;

创建 Google Drive 项目
  • 点击 “CREATE PROJECT” 进入创建项目页面;
创建项目页面
  • 输入 Project name,点击 “CREATE” 按钮;
  • 完成后会自动跳转到 Enabled APIs & services 页面,表示项目创建成功;
项目创建成功

2. 启用 Google API 与服务;

如上图,我们已经能使用某些开放的 API 了,但如果想要使用 Google Drive、Google Sheet,还需要启用 Google Drive API 与服务和Google Sheets API 与服务,步骤如下:

  • 点击 ENABLE APIS AND SERVICES 入口,跳转到 API Library 页面;
点击 ENABLE APIS AND SERVICES 入口 API Library 页面
  • 找到或搜索到 Google Drive API 入口;
找到 Google Drive API 入口 搜索到 Google Drive API 入口
  • 点击 Google Drive API 入口进入启用 Google Drive API 页面;
Google Drive API 入口
  • 点击 ENABE 按钮正式启用 Google Drive API;
Google Drive API 已启用

同时,我们会看到 APIs & Services 下多出了 Google Drive API

Google Drive API
  • 同样的办法,我们可以开放 Google Sheet API
搜索 Google Sheet API enable Google Sheet API Google Sheet API

3. 创建凭据;

  • 我们可以点击 CREATE CREDENTIALS 按钮进入创建凭据流程;
CREATE CREDENTIALS 1
  • 或者先点击左侧的 Credentials,再 CREATE CREDENTIALS 按钮进入创建凭据流程;
CREATE CREDENTIALS 2
  • 有几种凭据类型:
凭据类型

我们主要研究 2 种类型:API key 和 OAuth client ID;

(1). API key 的方式;

a. 点击选择 API key 方式;

API key 方式

b. 点击 Edit API key 入口可对 API key 进行使用限制,例如限制只能通过 HTTP 访问;

Edit API key

c. 然后我们就可以直接在 Google Drive API 的 url 上带上我们的 API key,如:
(获取 1v0-JXXXXXXXXXXXXGrU sheet 中名为 2022-03-31 ~ 2022-04-06 的 sheet tab,A1:C2 单元格的值)

https://sheets.googleapis.com/v4/spreadsheets/1v0-JXXXXXXXXXXXXGrU/values/2022-03-31%20~%202022-04-06!A1:C2?key=AIzYYYYYYYYYYYYYYYYY4
Rest API

注意:如果要用这种 Rest API 的方式,则我们的 Google 文件需要设置为:

public Google 文件

这个用起来挺方便的,不需要太多额外的操作,不过写代码的时候没有官方示例,要自己看 API 文档去做。

API 文档搜索入口:https://developers.google.com/apis-explorer/

API 文档搜索入口

Google Sheet API 文档:https://developers.google.com/sheets/api/reference/rest

(2). OAuth client ID 的方式;

这种方式稍微麻烦点,但也有其好处,从写代码的角度来看,Google Drive API 官方示例代码都是用这种方式写的,在写代码阶段,我们就可以直接拷贝 Google Drive API 官方示例代码,写起来会快速很多~

a. 点击选择 OAuth client ID;

(如果是第一次,那么还需要配置 CONSENT SCREEN);
b. 根据页面提示配置 CONSENT SCREEN;

配置 CONSENT SCREEN

c. 选择 User Type 为 Internal,然后点击 CREATE 按钮;

选择 User Type

d. 填写必要的信息后,点击 SAVE AND CONTINUE 按钮;

SAVE AND CONTINUE

点击多次保存或下一步直到 CONSENT SCREEN 配置完成;

e. 重新点击左侧的 “Credentials” 入口,再 CREATE CREDENTIALS 按钮正式开始创建 OAuth 凭据;

点击

f. 开始创建 OAuth 凭据;
(此处,选择 Application type 为 Desktop app)

开始创建 OAuth 凭据

g. 点击 CREATE 按钮即可创建完成;

凭据创建完成

当然,我们也可以用 Help me choose,让 Google 帮助我们决定(Service account 没用过不清楚)

4. 下载凭据;

对于 OAuth 类型,下载凭据很重要。

  • 点击创建完凭据后的弹窗的 DOWNLOAD JSON 按钮下载凭据;
点击 DOWNLOAD JSON
  • 或关闭弹窗后找到凭据,点击下载按钮再次打开弹窗:
下载入口

凭据是个 .json 文件,我们可以将它重命名为 credentials.json,凭据内容类似:

{
  "installed": {
    "client_id": "xxx",
    "project_id": "dylan-z-zhang-346506",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "yyy",
    "redirect_uris": [
      "http://localhost"
    ]
  }
}

5. 演示如何使用 Google API;

我们以 OAuth 方式为例,使用 Python,拿官网的例子直接稍微修改一下,操作我们的 Google Sheet.
(如果是 API key 的方式,API 文档请参考:https://developers.google.com/sheets/api/reference/rest)

Python 官网示例:https://github.com/googleworkspace/python-samples
(其他语言也可以在 https://github.com/orgs/googleworkspace/repositories 下找到)

我们创建一个项目,并且将 credentials.json 放在根目录下,并创建一个演示用的 python 文件,如:test.py

  • 编写代码
import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

SCOPES = ['https://www.googleapis.com/auth/spreadsheets', "https://www.googleapis.com/auth/drive"]


def create(title):
    credentials = None
    if os.path.exists('token.json'):
        credentials = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            credentials.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            credentials = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(credentials.to_json())

    try:
        service = build('sheets', 'v4', credentials=credentials)
        spreadsheet = {
            'properties': {
                'title': title
            }
        }
        spreadsheet = service.spreadsheets().create(body=spreadsheet,
                                                    fields='spreadsheetId') \
            .execute()
        print(f"Spreadsheet ID: {(spreadsheet.get('spreadsheetId'))}")
        return spreadsheet.get('spreadsheetId')
    except HttpError as error:
        print(f"An error occurred: {error}")
        return error


if __name__ == '__main__':
    create("mysheet1")

值得注意的是:

SCOPES = ['https://www.googleapis.com/auth/spreadsheets', "https://www.googleapis.com/auth/drive"]

这行指定了我们本次 Google API 操作的范围:
a. https://www.googleapis.com/auth/spreadsheets 允许我们对 Google Sheet 进行操作(Google 也提供了有一个跟这个对应的只读 scope,请自行了解)
b. https://www.googleapis.com/auth/drive 允许我们对 Google Drive 的文件夹操作等,在本例中 https://www.googleapis.com/auth/drive 不是必须的;

  • 安装 Google API client 依赖;
pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
  • 运行代码
python3 test.py

如果是第一次跑,那么还会自动打开 Sign in with Google 的页面,需要我们进行登录和允许相关功能的访问能力,第二次开始就不需要了。

Sign in with Google 页面 授权

完成后页面会显示:

The authentication flow has completed. You may close this window.
  • 完成后,项目下会多处一个 token.json 文件,文件中的内容类似:
{
  "token": "xxxxxx",
  "refresh_token": "yyyyy",
  "token_uri": "https://oauth2.googleapis.com/token",
  "client_id": "XXX",
  "client_secret": "YYYY",
  "scopes": [
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/drive"
  ],
  "expiry": "2022-04-07T10:50:58.703097Z"
}

再次运行代码即可访问 Google Sheet APIs.

  • 查看我们的 Google Drive;
通过 Google API 生成新的 Google Sheet

这是一个简单的例子,更多操作可以参考官网的例子,我们可以根据这些例子,组合出我们想要的功能,如给 Google Sheet 加 tab、Google Sheet 数据的增删改查等功能;

本文略长,但大部分的工作都是一次性的,后续使用 Google API 的话,就没那么繁琐了~

Google 有很多 API,很多功能,将来有机会可以多研究一些功能,咱再记录一下~

如果本文对您有帮助,麻烦点赞、关注!

谢谢!

相关文章

网友评论

      本文标题:如何使用 Google API

      本文链接:https://www.haomeiwen.com/subject/vxfjsrtx.html