How do I call a REST Google Cloud API from AppMaker?

回眸只為那壹抹淺笑 提交于 2019-12-11 05:42:56

问题


I want to call the Google Cloud AutoML API from AppMaker, but it's hard to figure out how to do that. How do I make a REST call to Google Cloud from AppMaker?


回答1:


First, follow the instructions here to generate a service account and download the private key. (I'm also assuming you already enabled the APIs for your project.)

Then, follow the instructions under the section "Addendum: Service account authorization without OAuth", but you will need to implement your own JWT encoding algorithm as follows:

var base64Encode = function (str) {
    var encoded = Utilities.base64EncodeWebSafe(str);
    // Remove padding
    return encoded.replace(/=+$/, '');
};

// https://developers.google.com/identity/protocols/OAuth2ServiceAccount
// https://wtfruby.com/gas/2018/11/21/jwt-app-scripts.html

var getJWT = function (secret) {
    var header = JSON.stringify({
        typ: 'JWT',
        alg: 'RS256',
        kid: '...'
    });
    var encodedHeader = base64Encode(header);
    var iat = new Date().getTime() / 1000;
    var exp = iat + 3600;
    var payload = JSON.stringify({
      iss: "...",
      sub: "...",
      aud: "https://automl.googleapis.com/",
      iat: iat,
      exp: exp
    });
    var encodedPayload = base64Encode(payload);
    var toSign = [encodedHeader, encodedPayload].join('.');
    var signature = Utilities.computeRsaSha256Signature(toSign, secret);
    var encodedSignature = base64Encode(signature);
    return [toSign, encodedSignature].join('.');
};
  • Get the API's service name and API name from the service definition file in the Google APIs GitHub repository
  • For the kid field in the header, specify your service account's private key ID. You can find this value in the private_key_id field of your service account JSON file.
  • For the iss and sub fields, specify your service account's email address. You can find this value in the client_email field of your service account JSON file.
  • For the aud field, specify https://SERVICE_NAME/, using the values from the service definition file.
  • For the iat field, specify the current Unix time, and for the exp field, specify the time exactly 3600 seconds later, when the JWT will expire.

Sign the JWT with RSA-256 using the private key found in your service account JSON file.

Then make the REST call as follows:

function makeRestCall() {

  var jwt = getJWT();
  var options = {
    'method' : 'post',
    'contentType': 'application/json',
    'headers': {
      'Authorization': 'Bearer ' + jwt, 
    },
    'muteHttpExceptions': true,
    'payload' : ...
  };

  var url = 'https://automl.googleapis.com/...';  
  return JSON.parse(UrlFetchApp.fetch(url, options).getContentText());
}


来源:https://stackoverflow.com/questions/58759042/how-do-i-call-a-rest-google-cloud-api-from-appmaker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!