要使用自己的Google Drive API,而不使用OAuth,可以使用服务账号凭据进行身份验证。下面是一个示例代码,演示了如何使用服务账号凭据进行身份验证和访问Google Drive API:
首先,创建一个服务账号并下载服务账号的凭据文件(通常为JSON格式)。
安装Google API 客户端库,假设你使用的是Python,可以使用以下命令进行安装:
pip install --upgrade google-api-python-client
import os
from googleapiclient.discovery import build
from google.oauth2.service_account import Credentials
# 加载服务账号凭据文件
credentials = Credentials.from_service_account_file('path/to/service_account_credentials.json')
# 构建Google Drive服务
drive_service = build('drive', 'v3', credentials=credentials)
# 示例:列出文件
results = drive_service.files().list(
pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
注意替换path/to/service_account_credentials.json
为你下载的服务账号凭据文件的路径。
以上代码示例将列出你的Google Drive中的文件。你可以根据自己的需求修改和扩展代码。
请注意,使用服务账号凭据进行身份验证时,你无法直接与用户的Google账号进行交互,因为它不涉及用户的授权。服务账号凭据允许你在没有用户干预的情况下访问你自己的Google Drive数据。