How to Await and Parse JSON from API Calls with UrlFetchApp in Apps Script

Apr 2, 2024 ยท 3 min read

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 UrlFetchApp methods like fetch() and getRequest() return a response object immediately before the API call completes. This means you need to handle the async nature of these calls properly with promises or async/await.

In this article, I'll walk through exactly how to:

  • Make a GET request with UrlFetchApp
  • Await the API response to ensure the data is returned before parsing
  • Parse and access the JSON data
  • 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 async. This allows us to use the await keyword inside the function.

    Awaiting the Fetch

    When calling UrlFetchApp.fetch(), we await the response. This pauses execution until the API call completes, ensuring we have access to the response data before trying to parse it.

    Parsing the Response

    Once we have the full response, we can get the content text with getContentText() and parse it into a JSON object with JSON.parse().

    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:

  • Use async/await properly to handle async nature
  • Always parse JSON with JSON.parse()
  • Handle errors and set timeouts
  • Access returned JSON object like regular JavaScript
  • With this approach, you'll be fetching and processing API data like a pro in Apps Script!

    Browse by language:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: