[英]Authorization error with Google apps script
我没有使用 Google Apps 脚本的经验。 我需要与外部 API 通信,但不断收到 {"error":"Authentication failed"} 响应。
如果有人能给我提示我应该在我的代码中更改什么,我将不胜感激。 我认为我写错了授权部分(在 API 文档中写道:授权:WebpageToken realm="api", apikey="testkey123")
下面是我正在尝试使用的 API 文档。
“API 文档:一些接口功能:承诺、员工、公司、客户/:id
API communication is done by RESTful-type HTTPS requests which are sent to: https://the.webpage.com/ {CUSTOMER_ID}/api/{ENDPOINT} Where {CUSTOMER_ID} is personal ID and {ENDPOINT} is interface function. 响应格式为 JSON。
示例请求(来自文档):
GET /1200/api/customers/1 HTTP/1.1
Host: the.webpage.com
Accept: application/json
Authorization: WebpageToken realm="api", apikey="testkey123"
”
我试图通过从 stackoverflow 和文档中搜索来找到编写授权的正确方法,但运气不好。
我在 Google Apps 脚本中的代码:
function getCorporates(){
var ENDPOINT = "corporates";
var apiKey = ”testkey123”; //example
var CUSTOMER_ID = 1234; //example
var options = {
"method":"GET",
"muteHttpExceptions": true,
"Authorization":{
"WebpageToken":{
"realm":"api",
"apikey" :apiKey
}
}
};
var url = "https://the.webpage.com/" + CUSTOMER_ID + "/api/" + ENDPOINT;
var response = UrlFetchApp.fetch(url, options); // get api endpoint
var json = response.getContentText(); // get the response content as text
Logger.log(json); //log data to logger to check
}
此代码应返回 JSON object。 目前我收到 {"error":"Authentication failed"} 响应。
请注意,我必须“隐藏”公司名称,因此在这种情况下,它已更改为 the.webpage.com,这不是我尝试调用的真正 API 地址。
感谢帮助!
您需要将Authorization
添加为header ,如下所示:
var headers = {
"Authorization" : "Webpage realm='api', apikey='testkey123'"
};
var params = {
"method": "GET",
"muteHttpExceptions": true,
"headers": headers
};
var response = UrlFetchApp.fetch(url, params);
换句话说,HTTP 标头是它们自己的 object params
object (来自我的示例,来自您的示例的options
)。
请参阅“高级参数”下的文档 [0]
[0] https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.