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

在Streamlit中验证YouTube Data API v3遇密钥无效问题求助

问题:Streamlit调用YouTube Data API v3时出现API密钥无效错误

环境与代码说明

我正在使用Streamlit部署一款调用YouTube Data API v3查询频道URL的应用,核心配置代码如下:

default_api_key = "..."  # API key
API_KEY = st.text_input("Enter your YouTube API Key", value=default_api_key, type="password")
API_service_name = 'youtube'
API_version = 'v3'
youtube = build(API_service_name, API_version, developerKey=API_KEY)

同时编写了get_uploads_playlist_id这类接口调用函数,示例代码:

def get_uploads_playlist_id(api_key, channel_id):
    url = 'https://www.googleapis.com/youtube/v3/channels'
    params = {
        'part': 'contentDetails',
        'id': channel_id,
        'key': api_key
    }
    
    response = requests.get(url, params=params)
    
    if response.status_code != 200:
        print(f'Error: {response.status_code} - {response.text}')
        return None
    
    data = response.json()
    
    if 'items' not in data or len(data['items']) == 0:
        print(f'No details found for channel ID: {channel_id}')
        return None
    
    uploads_playlist_id = data['items'][0]['contentDetails']['relatedPlaylists']['uploads']
    return uploads_playlist_id

该函数通过playlist_id = get_uploads_playlist_id(API_KEY, value)进行调用。

错误现象

本地运行Streamlit应用时触发400错误:

Error: 400 - {
"error": {
"code": 400,
"message": "API key not valid. Please pass a valid API key.",
"errors": [
{
"message": "API key not valid. Please pass a valid API key.",
"domain": "global",
"reason": "badRequest"
}
],
"status": "INVALID_ARGUMENT",
"details": [
{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "API_KEY_INVALID",
"domain": "googleapis.com",
"metadata": {
"service": "youtube.googleapis.com"
}
}
]
}
}

但在本地Jupyter Notebook中移除Streamlit组件后,代码运行完全正常。我已为Streamlit创建Client ID并配置正确的URI,不确定是Python文件中API密钥的问题,还是与第三方框架连接的问题。曾尝试参考相关教程使用凭据,但不确定步骤是否过时或操作有误,其中涉及Google ID Token的获取,不清楚如何操作,也不确定该方式是否已废弃。完整代码已移除API密钥。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 06:11:03