Ethereum: UrlFetchApp request fails in Menu Functions but not in Custom Functions (connecting to external REST API)
Here is an example article based on your query:
Ethereum: UrlFetchApp request fails in menu functions but not custom functions
As a developer working with Google Apps Script, you are probably no stranger to the challenges of connecting to external APIs. Recently, I ran into an issue where my UrlFetchApp
requests failed when trying to fetch market prices from an external REST API, but not when using custom functions.
The problem: External API request
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 failed with an error message stating that the URL was malformed. After further investigation, I realized that the issue was not related to an issue with the API endpoint itself, but rather with how UrlFetchApp
is configured.
Custom Function Solution
When using custom functions, the issue can be more complex and requires careful consideration of how to handle HTTP requests.
After some research and experimentation, I found that if you are making HTTP requests from within a custom function, it is essential to use the URL
object instead of UrlFetchApp
. Specifically, 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.here, options);
var data = JSON.parse(response.getContentText());
return data ;
} }
The key difference between using UrlFetchApp
and creating a new URL
object is that the former uses the href
property of the resulting URL, which allows you to easily add query parameters (such as the symbol). This approach works in both menu functions and custom functions.
Conclusion
In conclusion, if you are having issues with external API requests when using UrlFetchApp
, but not when using custom functions, it is likely due to the way HTTP requests are configured within your script. By switching from UrlFetchApp
to creating a new URL
object or adding query parameters directly to the resulting URL, you should be able to resolve the issue and successfully retrieve market prices from an external REST API.
I hope this article was helpful in resolving the issue!