API Requests
How to make API requests in JavaScript.
GET request
// API for get requests
let res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
let json = await res.json();
console.log(json);
return [Object.keys(json), Object.values(json)];GET request with error handling
async function getData() {
const url = "https://jsonplaceholder.typicode.com/todos/1";
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const json = await response.json();
// Return the JSON object as a 2D array
return [Object.keys(json), Object.values(json)];
} catch (error) {
console.error(error.message);
// Return the error message to the sheet
return `Error: ${error.message}`;
}
}
// Call the function and return its result to the sheet
return await getData();POST request with body
Last updated
Was this helpful?