Reputation: 173
I'm using a Google App Script to request API data from a website and then record the data that I receive in a Google Sheet. The problem I have is that the website I'm requesting the data from requires two things: my auth key and a specific (static) IP address. It automatically records the IP address that makes the request and it will not let me get the data if I use the wrong IP address. Google App Script API requests, unfortunately, use a range of dynamic IPs, and I can only allow up to 5 different IPs to work with my auth key. Is there any way to specify which IP address my Google App Script will use to send my API request?
Below you can see my code; it all works fantastically when the IP address matches up with what I've written on the website, but it returns undefined if it uses an unknown IP address.
function fetchAPI(tag) {
var url = 'https://myurl'
+ tag;
var token = {'muteHttpExceptions': true};
token.headers = {'Accept': 'application/json','authorization': 'my auth key'};
var response = UrlFetchApp.fetch(url, token);
return JSON.parse(response);
}
Another option I thought of was to create multiple API keys, one for every 5 IP addresses, but the problem with this is that Google's range of IPs covers hundreds of different addresses: https://developers.google.com/apps-script/guides/jdbc#accessing
If you can think of anything at all that might help, it would be appreciated! Or if you can think of a way to proxy my request through a static IP address (without having to pay money to host my own website), please let me know!
Upvotes: 1
Views: 1396
Reputation: 7983
According to this blog, the writer has observed a pattern in ip usage in google script :
Therewere two clear observations:
- IP may vary in consecutive calls within one trigger
- There is a clear rotation of the IPs, sometimes there is a group of 7 consecutive calls with the same IP, sometimes 6. But in general there are always groups.
Hence it is possible to use the solution of repeatedly calling to the server till it succeeds:
function batchRequest(userLogin, userPassword, webapiKey, resource, attributes, values ){
var token = requestToken(userLogin, userPassword, webapiKey ); // requestToken method uses UrlFetchApp.fetch
var result = request(resource, token, attributes, values);
/** requestToken method uses UrlFetchApp.fetch with options.muteHttpExceptions set to true so that we can read the response code **/
var i = 0;
while (result.getResponseCode() == 500 && i < 10){
token = requestToken(userLogin, userPassword, webapiKey ); // requestToken method uses UrlFetchApp.fetch
result = request(resource, token, attributes, values);
i++;
}
return result;
}
You can vary the number of iterations based on the best result.
Upvotes: 1