问题
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