How to fetch external API data into Google Sheets with Apps Script

I want to pull information from a third party REST API and put it into my Google spreadsheet using Google Apps Script. I found an API endpoint that has the data I need but I’m stuck on how to properly handle the response and extract the specific fields I want.

Here’s what I have so far:

function fetchAPIData() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var dataSheet = spreadsheet.getSheetByName("Data");
  
  dataSheet.getRange('B2').clearContent();
  
  var apiEndpoint = "https://api.example.com/bookings/availability";
  
  var apiResponse = UrlFetchApp.fetch(apiEndpoint);
  var jsonText = apiResponse.getContentText();
  var parsedData = JSON.parse(jsonText);
  
  var bookingDate = parsedData.results.
}

I’m really new to working with APIs and Google Apps Script so I’m not sure how to continue from here. How do I access nested properties in the JSON response and write them to specific cells? Any help would be great!

Your main issue is figuring out the JSON structure you’re getting back. Add this debug line right after parsing: Logger.log(JSON.stringify(parsedData, null, 2)) then check the execution log to see exactly what you’re working with. Most booking APIs I’ve worked with return arrays of objects. You’ll probably need parsedData.results[0].date if results is an array, or parsedData.results.date if it’s a single object. Just match your property access to whatever structure you actually get. One thing that’s bitten me multiple times - wrap your UrlFetchApp call in try-catch. External APIs fail way more than you’d think, and there’s nothing worse than your script breaking silently because the API returned an error instead of proper JSON.

The Problem:

You’re trying to pull data from a third-party REST API into your Google Sheet using Google Apps Script, but you’re having trouble accessing nested properties within the JSON response and writing them to specific cells. Your current script is incomplete and doesn’t handle potential errors.

:thinking: Understanding the “Why” (The Root Cause):

Google Apps Script relies on proper JSON parsing and understanding the structure of the API response. Incorrectly accessing nested properties will lead to errors. Furthermore, external APIs can be unreliable; they may return unexpected responses or errors, so error handling is crucial. Finally, efficiently writing data to your sheet requires understanding how to address specific cells and handle potential issues like empty or malformed responses.

:gear: Step-by-Step Guide:

Step 1: Inspect the API Response:

Before attempting to access nested properties, it’s essential to understand the structure of the JSON data returned by the API. Add a console.log() statement to examine the response:

function fetchAPIData() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var dataSheet = spreadsheet.getSheetByName("Data");

  dataSheet.getRange('B2:C2').clearContent(); // Clear a range to avoid overwriting data

  var apiEndpoint = "https://api.example.com/bookings/availability";

  try {
    var apiResponse = UrlFetchApp.fetch(apiEndpoint);
    var jsonText = apiResponse.getContentText();
    var parsedData = JSON.parse(jsonText);
    console.log(JSON.stringify(parsedData, null, 2)); // Log the parsed JSON for inspection


    //Check if the API returns an array
    if (Array.isArray(parsedData.results)){
        // Accessing an array of objects.  Assume at least one object exists. Adjust the index [0] if needed.
      var bookingDate = parsedData.results[0].date;
      var bookingStatus = parsedData.results[0].status; // Example property; adjust as needed

      dataSheet.getRange('B2').setValue(bookingDate);
      dataSheet.getRange('C2').setValue(bookingStatus);
    } else if (parsedData.results){
        // Accessing a single object
      var bookingDate = parsedData.results.date;
      var bookingStatus = parsedData.results.status; // Example property; adjust as needed

      dataSheet.getRange('B2').setValue(bookingDate);
      dataSheet.getRange('C2').setValue(bookingStatus);
    } else {
      Logger.log("Error: 'results' property not found or empty.");
    }


  } catch (error) {
    Logger.log("An error occurred: " + error);
  }
}

Open your script’s execution log (View > Logs) to see the formatted JSON response. This will clearly show the structure and the correct path to access the date and other properties. Modify the code to correctly extract the desired fields based on this structure. Remember to replace example properties (date, status) with the actual property names from your API response.

Step 2: Handle Errors and Empty Responses:

The try...catch block handles potential errors during the API call or JSON parsing. The conditional checks (if (Array.isArray(parsedData.results)) and if (parsedData.results)) ensure that the script gracefully handles cases where the results property is missing or empty.

Step 3: Write to the Spreadsheet:

The script uses setValue() to write the extracted data to cells B2 and C2. Adjust cell references and property names as needed. Clearing a range (dataSheet.getRange('B2:C2').clearContent()) prevents overwriting existing data.

:mag: Common Pitfalls & What to Check Next:

  • API Authentication: Many APIs require authentication (API keys, OAuth tokens). Check the API documentation and add appropriate headers to your UrlFetchApp.fetch request.
  • API Rate Limits: If you’re making many API calls, respect the API’s rate limits. Use Utilities.sleep() to pause your script between calls.
  • Data Formatting: Ensure the date property from the API is in a format Google Sheets can understand. You might need to use Utilities.formatDate() to convert it.
  • Error Logging: The Logger.log() statements are crucial for debugging. Use them to check the values of variables at different stages of your script. Thoroughly examine the logs to determine the exact location and type of errors, and adapt your code accordingly.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

Nested JSON in Apps Script seems tricky at first, but it’s pretty straightforward once you get the hang of it. You just need to figure out whether you’re dealing with arrays or objects. I always log the response first to see what I’m actually working with: javascript console.log(parsedData); Then navigate through it properly. Arrays need bracket notation with an index, objects use dot notation: javascript var bookingDate = parsedData.results[0].booking_date; var status = parsedData.results[0].status; dataSheet.getRange('B2').setValue(bookingDate); dataSheet.getRange('C2').setValue(status); Add error handling around your fetch and JSON parsing - APIs throw curveballs. Learned this when my script died because the API went down. Try-catch blocks will save you tons of headaches.

Check if the API needs auth headers first! Most APIs want a token or key. Add it like this: var options = {headers: {'Authorization': 'Bearer yourtoken'}}; var apiResponse = UrlFetchApp.fetch(apiEndpoint, options); Watch the rate limits too - use Utilities.sleep() between calls when fetching lots of data or you’ll get blocked.

Your code’s almost there - just finish the property chain. First, add console.log(parsedData) right after JSON.parse to see what structure you’re actually getting. Most booking APIs I’ve worked with need something like parsedData.results[0].booking_date if results is an array of booking objects. Once you see the structure, you can grab multiple fields at once and write them to different cells. I always check for empty responses since booking APIs sometimes return null during off-peak times. Use if (parsedData.results && parsedData.results.length > 0) before accessing data - prevents crashes on empty responses. Also, booking data changes a lot, so clear a range of cells first instead of just B2.

Your code’s a decent start, but you’ll hit problems fast with this approach.

For nested JSON properties, continue like this:

var bookingDate = parsedData.results[0].date; // if results is an array
var availability = parsedData.results.availability; // if it's an object
dataSheet.getRange('B2').setValue(bookingDate);

Here’s the issue - Apps Script for API integrations gets messy quick. You’ll need error handling, rate limiting, data transformation, plus scheduling. When the API changes or you add more data sources, you’re rewriting everything.

I’ve done this too many times. Now I skip custom scripting and use Latenode instead. Connect your API endpoint visually, map the fields, and it pushes to Google Sheets automatically.

No debugging, built-in error handling, runs on any schedule you want. Takes 5 minutes versus hours of scripting and testing.

Saves me about 10 hours per integration compared to custom Apps Script.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.