Making API calls is extremely common when building applications with Apps Script. Often, these API endpoints return JSON data that needs to be processed. The UrlFetchApp service in Apps Script provides a way to make HTTP requests and handle the responses.
However, one complexity is that
In this article, I'll walk through exactly how to:
I'll also share some tips and tricks around error handling and setting timeouts.
Let's dive in with a simple code example:
async function getJson() {
const url = "https://api.example.com/data";
const response = await UrlFetchApp.fetch(url);
const json = JSON.parse(response.getContentText());
Logger.log(json); // log parsed JSON data
}
There are a few key aspects that make this work properly:
Async Function
The outer function is declared as
Awaiting the Fetch
When calling
Parsing the Response
Once we have the full response, we can get the content text with
Now let's explore some more advanced topics around handling errors, timeouts, and processing the JSON data.
Handling Errors
It's always a good idea to wrap your API calls in try/catch blocks to gracefully handle errors:
async function getJson() {
try {
const url = "https://api.example.com/data";
const response = await UrlFetchApp.fetch(url);
const json = JSON.parse(response.getContentText());
} catch (error) {
Logger.log(error); // log error details
}
}
This catches things like network errors, invalid JSON responses, etc.
Setting Timeouts
You can also set a timeout in milliseconds to avoid hanging if an API call gets stuck:
const response = await UrlFetchApp.fetch(url, {
timeout: 3000 // 3 seconds
});
If a timeout occurs, it will reject the promise and enter the catch block.
Processing the JSON
Once you have parsed the JSON data, you can access it like any other JavaScript object:
const json = JSON.parse(response.getContentText());
// Log specific field
Logger.log(json.results[0].name);
// Loop through data
json.results.forEach(result => {
Logger.log(result);
});
Access and manipulate the JSON as needed for your application!
Key Takeaways
Making API calls in Apps Script and processing JSON responses is very common. Here are some key tips:
With this approach, you'll be fetching and processing API data like a pro in Apps Script!