我正在使用youtube api。当我点击此网址“ https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DMINE&start-date=2015-01-01&end-date=2016-01-31&metrics=likes%2Cdislikes&key= {API Key} ”
时它给出了401
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
但是我在探险家“https://developers.google.com/apis-explorer/中找到了什么?”
它工作正常。
如何使第一个请求有效?
答案 0 :(得分:14)
在您的请求中,您发送密钥= {your key}以获取您应发送的访问令牌access_token = {your oauth2 access token}
注意:密钥用于公共请求。访问令牌用于经过身份验证的请求。
答案 1 :(得分:3)
如果在Google API上使用JWT身份验证的其他人偶然发现此问题(例如,在使用服务帐户时),请务必在API调用中加入auth: <your jwtClient>
,例如:
首先,获取令牌:
// Configure JWT auth client
var privatekey = require("./<secret>.json")
var jwtClient = new google.auth.JWT(
privatekey.client_email,
null,
privatekey.private_key,
['https://www.googleapis.com/auth/drive']
);
// Authenticate request
jwtClient.authorize(function (err, tokens) {
if (err) {
return;
} else {
console.log("Google autorization complete");
}
});
然后,调用API (但不要忘记auth:jwtClient
部分)
drive.files.create({
auth: jwtClient,
resource: {<fileMetadata>},
fields: 'id'
}, function (err, file) {
if (err) {
// Handle error
} else {
// Success is much harder to handle
}
});