Here is a sample article based on your request:
Ethereum: urlftchapp Request Fails in menu functions but not in custom functions
As a developer working with Google apps script, you’re likely no stranger to the challenges of connecting to external apis. Recently, I Encountered An Issue Where My Urlfetchapp
Requests Were Failing When trying to Retrieve Market Prices From An External Rest API, But Not When Using Custom Functions.
The issue: External API Request
When I Used the Following Code in A Menu Function:
`Javascript
Function Getmarketprices () {
Var Options = {
method: ‘get’,
headers: {
‘Content-Type’: ‘Application/JSON’
}
};
Var response = urlfthapp.fetch (‘ Options);
Var Data = Json.Parse (response.gettenttext ());
Return data;
}
`
The Request was failing with an error message indicating that the url was malformed. Upon Further Investigation, I realized that the issue was not related to a problem with the api endpoint itself, but rather with how urlfthapp '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 discovered that if you're making http requests from within a custom function, it's essential to use theURLobject adjusting or
urlfetchapp. Specifically, When Creating A New
URLObject For An External API Request:
Javascript
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 = urlftchapp.fetch (url.href, options);
Var Data = Json.Parse (response.gettenttext ());
Return data;
}
`
The Key Difference Between Using UrlfThapp
And Creating A NewUrl
Object Is that the Former Uses the Href
Property of the resulting Url, which allows you to append query parameters (Like the Symbol) Easily. This approach works in Both Menu functions and custom functions.
Conclusion
In Conclusion, if you’re experienced issues with external API requests when using urlfetchApp
, but not when using custom functions, it’s likely due to how http requests are bee configured within your script. By Switching from urlfthapp
to create a newURL
object or appning query parameters Directly to the resulting url, you should be able to resolve the Issue and Successully Retrieve Market Prices from an External Rest API.
I hope this article has bone helpful in resolving the issue for you!