如何在Google Colab中解决YouTube API OAuth 2.0授权400错误
问题根因
你遇到的报错核心来自两个配置误区:
- 你使用的YouTube公开搜索接口仅需API密钥即可调用,完全不需要走OAuth2.0授权流程。弹出授权提示是因为代码配置错误,触发了Google客户端库默认的凭证回退逻辑,才会拉起不必要的授权流程。
redirect_uri_mismatch报错是因为Google Colab属于Web托管环境,早已不支持旧版原生应用专用的urn:ietf:wg:oauth:2.0:oob(带外回调)地址,你之前添加Colab域名到重定向列表的操作无效,本质是用错了认证方式。
方案一:公开数据搜索场景(无需OAuth,推荐优先使用)
针对普通搜索需求,直接用API密钥调用即可,完全跳过授权流程,步骤如下:
- 进入Google云控制台,创建对应项目,启用YouTube Data API v3,创建API密钥(不需要创建OAuth客户端ID),复制生成的密钥字符串备用。
- 在Colab中先安装/升级依赖,运行如下代码块:
!pip install --upgrade google-api-python-client
- 替换原Python2版本示例代码(原代码是Python2语法,Colab默认Python3环境直接运行会报语法错),将
REPLACE_ME替换为你复制的API密钥,完整可运行代码如下:
from googleapiclient.discovery import build from googleapiclient.errors import HttpError # 替换为你自己的API密钥 DEVELOPER_KEY = 'REPLACE_ME' YOUTUBE_API_SERVICE_NAME = 'youtube' YOUTUBE_API_VERSION = 'v3' def youtube_search(q, max_results=25): youtube = build( YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY, cache_discovery=False ) search_response = youtube.search().list( q=q, part='id,snippet', maxResults=max_results ).execute() videos = [] channels = [] playlists = [] for search_result in search_response.get('items', []): res_kind = search_result['id']['kind'] if res_kind == 'youtube#video': videos.append(f"{search_result['snippet']['title']} ({search_result['id']['videoId']})") elif res_kind == 'youtube#channel': channels.append(f"{search_result['snippet']['title']} ({search_result['id']['channelId']})") elif res_kind == 'youtube#playlist': playlists.append(f"{search_result['snippet']['title']} ({search_result['id']['playlistId']})") print("Videos:\n", "\n".join(videos), "\n") print("Channels:\n", "\n".join(channels), "\n") print("Playlists:\n", "\n".join(playlists), "\n") if __name__ == '__main__': try: youtube_search(q='surfing', max_results=10) except HttpError as e: print(f"An HTTP error {e.resp.status} occurred:\n{e.content}")
- 如果之前运行过错误的认证代码,先点击Colab顶部菜单「运行时」→「重置所有运行时」,清除缓存的错误凭证配置,再运行上述代码即可直接返回结果,不会弹出任何授权提示。
方案二:需要访问用户私有数据场景(必须使用OAuth2.0)
如果你的需求涉及访问用户私有播放列表、上传视频等需要账号授权的操作,按如下步骤配置避免回调错误:
- 进入Google云控制台,创建OAuth客户端ID,应用类型选择Web应用。
- 在该客户端的「已获授权的重定向URI」列表中添加
https://localhost:8080/,保存配置。 - 在Colab中安装依赖,使用适配Colab环境的授权流程,不要直接用官方原生应用示例代码:
!pip install --upgrade google-api-python-client google-auth-oauthlib from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build # 替换为你自己的OAuth客户端配置信息 CLIENT_CONFIG = { "installed": { "client_id": "你的客户端ID", "client_secret": "你的客户端密钥", "redirect_uris": ["https://localhost:8080/"], "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token" } } # 替换为你需要的API权限范围 SCOPES = ["https://www.googleapis.com/auth/youtube.readonly"] # 启动本地服务授权流程,Colab会自动做端口转发,不会触发OOB回调错误 flow = InstalledAppFlow.from_client_config(CLIENT_CONFIG, SCOPES) credentials = flow.run_local_server(port=8080) youtube = build('youtube', 'v3', credentials=credentials) # 后续可正常调用需要授权的接口
- 运行代码后点击弹出的授权链接,登录账号完成授权即可,不会再出现重定向URI不匹配的报错。
常见踩坑说明
- 不要使用旧版OOB回调地址
urn:ietf:wg:oauth:2.0:oob,Google自2022年10月起已停止Web环境对该地址的支持,Colab环境下使用必然报错。 - 公开数据查询优先使用API密钥,不需要走OAuth流程,配置更简单,配额也能满足普通搜索需求。
- 只要代码中
build方法正确传入developerKey参数、没有传入credentials参数,就不会自动拉起OAuth授权流程。
内容的提问来源于stack exchange,提问作者Marco Aurelio Fernandez Reyes
相关产品推荐
相关产品推荐

