You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google Cloud Function写入Google Sheet遇403权限错误求助

Google Cloud Function写入Google Sheet报403权限错误排查

问题场景

本地运行Python脚本时,指定服务账号凭据可正常写入Google Sheet,但部署到Google Cloud Function后执行报错403,提示「请求缺少有效的API密钥」。使用服务账号身份验证,而非OAuth客户端ID。

代码示例

import pygsheets
import pandas as pd
import google.auth
from googleapiclient.discovery import build


def gen_google_sheet():
    """
    Get the service credentials to be used to query a google sheet
    """
    #scope for read and write
    scopes = ['https://www.googleapis.com/auth/spreadsheets']
    creds, project = google.auth.default(scopes=scopes)
    service = build('sheets', 'v4', credentials=creds)
    #authorization
    gc = pygsheets.authorize(credentials=creds)
    """
    gc = pygsheets.authorize(service_file='compute_engine_service_acc_api_key.json')
    """

    # Create empty dataframe
    df = pd.DataFrame()

    # Create a column
    df['name'] = ['John', 'Steve', 'Sarah']

    #open the google spreadsheet (where 'PY to Gsheet Test' is the name of my sheet)
    sh = gc.open('Python Write Test')

    #select the first sheet 
    wks = sh[0]

    #update the first sheet with df, starting at cell B2. 
    return wks.set_dataframe(df,(1,1))

错误信息

{
"error": {
"code": 403,
"message": "The request is missing a valid API key.",
"errors": [
{
"message": "The request is missing a valid API key.",
"domain": "global",
"reason": "forbidden"
}
],
"status": "PERMISSION_DENIED"
}
}

排查与解决方案

1. 检查Cloud Function默认服务账号的Sheet访问权限

Cloud Function默认使用[你的项目ID]@appspot.gserviceaccount.com服务账号,需将该账号添加到目标Google Sheet的共享列表,授予编辑权限。

2. 简化代码,移除冗余服务构建

代码中build('sheets', 'v4', credentials=creds)属于冗余代码,pygsheets会自行初始化Google Sheets服务,保留该代码可能导致凭据传递冲突。修改后的代码如下:

import pygsheets
import pandas as pd
import google.auth

def gen_google_sheet():
    # 读写权限范围
    scopes = ['https://www.googleapis.com/auth/spreadsheets']
    # 获取Cloud Function默认服务账号凭据
    creds, _ = google.auth.default(scopes=scopes)
    # 初始化pygsheets客户端
    gc = pygsheets.authorize(credentials=creds)

    # 构造测试数据
    df = pd.DataFrame({'name': ['John', 'Steve', 'Sarah']})

    # 打开目标表格
    sh = gc.open('Python Write Test')
    # 选择第一个工作表
    wks = sh[0]
    # 从A1单元格开始写入数据
    wks.set_dataframe(df, (1, 1))
    return "数据写入完成"

3. 确认Google Sheets API已启用

在Google Cloud控制台中,搜索并启用Google Sheets API,否则即使权限配置正确,也无法调用相关接口。

备选方案:使用服务账号密钥文件(不推荐,需管理密钥)

如果默认凭据仍有问题,可将服务账号密钥文件打包到Cloud Function部署包中,修改授权代码:

# 替换原授权代码为以下内容
gc = pygsheets.authorize(service_file='your-service-account-key.json')

注意:部署时需确保密钥文件在函数工作目录下,且不要将密钥文件提交到版本控制系统。

内容的提问来源于stack exchange,提问作者Becky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 04:32:48