Here is an example article based on your request:
Ethereum: UrlFetchApp request fails in menu functions but not in custom functions
As a developer working with Google Apps Script, you are probably no stranger to the challenges of connecting to external APIs. I recently encountered an issue where my UrlFetchApp
requests were failing when trying to fetch market prices from an external REST API, but not when using custom functions.
Problem: Requesting an external API
When I used the following code in a menu function:
function getMarketPrices() {
var options = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
var response = UrlFetchApp.fetch(' options);
var data = JSON.parse(response.getContentText());
return data;
}
The request was failing with an error message indicating that the URL was invalid. After further investigation, I realized that the problem was not with the API endpoint itself, but rather with the way UrlFetchApp
was configured.
Custom Function Solution
When using custom functions, the problem can be more complex and requires careful consideration of how HTTP requests are handled.
After some research and experimentation, I found that if you are sending HTTP requests from a custom function, it is necessary to use the URL
object instead of UrlFetchApp
. More precisely, when creating a new URL
object for an external API request:
function getMarketPrices() {
var options = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
var url = new URL('
url.searchParams.set('symbol', 'BTCUSDT'); // Replace with the desired symbol
var response = UrlFetchApp.fetch(url.href, options);
var data = JSON.parse(response.getContentText());
return data;
}
The main difference between using UrlFetchApp
and creating a new URL
object is that the former uses the href
property of the resulting URL, which allows for easy appending of query parameters (such as a symbol). This approach works for both menu functions and custom functions.
Conclusion
In conclusion, if you are having problems with external API requests when using UrlFetchApp
but not when using custom functions, it is probably due to the way you are configuring HTTP requests in your script. By switching from UrlFetchApp
to creating a new URL
object or appending query parameters directly to the resulting URL, you should be able to resolve the issue and successfully fetch market prices from an external REST API.
I hope this article was helpful in resolving your issue!