我正在尝试使用 Python 连接到 YouTube Analytics API。当我转到“凭据”选项卡中的 Google 开发者控制台时,单击创建凭据
下拉菜单,然后选择帮助我选择
。我点击我想要使用的 API (YouTube Analytics API
),我将从其中调用 (其他非 UI(例如 cron 作业、守护进程)
),什么我将访问的数据(应用程序数据
),然后是我是否使用 Google App Engine(否
)。我单击按钮查看我需要哪些凭据,它告诉我您已经拥有适合此目的的凭据
。
我有一个服务帐户
,用于连接到 Google Search Console API 以访问我公司拥有的多个网站的数据。因为我们有多个站点,所以我根据我的电子邮件地址使用委派凭据。这是我用于向 Search Console API 进行身份验证的代码:
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
scopes = ['https://www.googleapis.com/auth/webmasters.readonly']
credentials = ServiceAccountCredentials.from_json_keyfile_name('keyfile.json', scopes=scopes)
delegated_credentials = credentials.create_delegated('<my-email>')
http_auth = delegated_credentials.authorize(Http())
webmasters_service = build('webmasters', 'v3', http=http_auth)
现在,我尝试对 YouTube Analytics API 使用类似的方法,但收到此错误:HttpAccessTokenRefreshError:unauthorized_client:请求中的客户端或范围未经授权。
。这是我的代码:
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
START_DATE = "2016-09-01"
END_DATE = "2016-09-30"
scopes = ['https://www.googleapis.com/auth/yt-analytics.readonly']
credentials = ServiceAccountCredentials.from_json_keyfile_name('keyfile.json', scopes=scopes)
delegated_credentials = credentials.create_delegated('<my-email>')
http_auth = delegated_credentials.authorize(Http())
youtube_service = build('youtubeAnalytics', 'v1', http=http_auth)
analytics_query_response = youtube_service.reports().query(
ids="channel==<my-youtube-channel-id>",
metrics="views",
start_date=START_DATE,
end_date=END_DATE
).execute()
keyfile.json
与我用于连接到 Search Console API 的文件(包含服务帐户凭据)相同。我什至尝试创建一个新的服务帐户并使用这些凭据,但我没有任何运气。是的,我已在开发者控制台中启用了所有 YouTube API。
您知道为什么我会收到 HttpAccessTokenRefreshError: Unauthorized_client: ...
错误吗?
编辑:以前我使用 OAuth ID 而不是服务帐户,当我运行脚本时,会出现一个浏览器选项卡,我必须选择一个帐户。我有两个选项:一个是我的电子邮件,另一个是我被添加为管理员的 YouTube 帐户。您认为我收到该错误是因为我使用电子邮件地址(而不是 YouTube 帐户)生成凭据吗?
edit2:YouTube 帐户似乎不属于我们的 Google Apps 域的保护范围。因此,这可能就是为什么我无法授权使用我的电子邮件地址,即使我已被任命为使用该电子邮件地址的 YouTube 帐户的管理员。
最佳答案
我发现了这个documentation您无法将服务帐户与 YouTube Analytics API 结合使用。
这里声明:
The service account flow supports server-to-server interactions that do not access user information. However, the YouTube Analytics API does not support this flow. Since there is no way to link a Service Account to a YouTube account, attempts to authorize requests with this flow will generate an error.
我也在这个thread中找到了它由 Google 员工回答。
有关更多信息,请查看此 SO question .
关于python - Google API 授权(服务帐户)错误 : HttpAccessTokenRefreshError: unauthorized_client: Unauthorized client or scope in request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40027878/