Here’s 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’re probably no stranger to the challenges of connecting to external APIs. I recently 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.
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());
data returned;
}
The request failed with an error message stating that the URL is incorrect. After further investigation, I realized that the issue was not with the API endpoint itself, but rather with the configuration of “UrlFetchApp”.
Custom Function Solution
When using custom functions, the issue 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 making HTTP requests from 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 desired symbol
var response = UrlFetchApp.fetch(url.href, options);
var data = JSON.parse(response.getContentText());
data returned;
}
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 with both menu 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 in the 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!