Perform API requests using the standard JavaScript approach of Fetch.
// API for get requestslet res =awaitfetch("https://jsonplaceholder.typicode.com/todos/1");let json =awaitres.json();console.log(json);return [Object.keys(json),Object.values(json)];
GET request with error handling
asyncfunctiongetData() {consturl="https://jsonplaceholder.typicode.com/todos/1";try {constresponse=awaitfetch(url);if (!response.ok) {thrownewError(`Response status: ${response.status}`); }constjson=awaitresponse.json();// Return the JSON object as a 2D arrayreturn [Object.keys(json),Object.values(json)]; } catch (error) {console.error(error.message);// Return the error message to the sheetreturn`Error: ${error.message}`; }}// Call the function and return its result to the sheetreturnawaitgetData();
POST request with body
asyncfunctiongetData() {// replace with your API URL and body parameters consturl="https://example.org/products.json";constrequestBody= { key1:"value1", key2:"value2" };try {constresponse=awaitfetch(url, { method:"POST", headers: {"Content-Type":"application/json" }, body:JSON.stringify(requestBody) });if (!response.ok) {thrownewError(`Response status: ${response.status}`); }constjson=awaitresponse.json();// Return the JSON object as a 2D arrayreturn [Object.keys(json),Object.values(json)]; } catch (error) {console.error(error.message);// Return the error message to the sheetreturn`Error: ${error.message}`; }}// Call the function and return its result to the sheetreturnawaitgetData();
If you ever get stuck with JavaScript code (especially requests) that doesn't seem to be working but is showing no error, you may be missing an Await somewhere that it is needed.