Hands-On AI WorkshopHomeProjectsLearnResourcesPresenterHelpProgress

Project 04 of 30 · Pathway 1 — Spreadsheet Automation

External API Data Importer

Copying external API records manually wastes time. Import public JSON into a spreadsheet.

Real-world benefit
Public data feeds and directory imports.
Technologies
UrlFetchApp, HTTP, JSON, Google Sheets
Required knowledge
What a URL is. JSON is explained in the walkthrough.
Time and level
About 25 minutes · Intermediate
AI requirement
None: deterministic Apps Script
Expected baseline
Three user rows if endpoint is available; first user Leanne Graham.

Loading the interactive studio…

Introduction

Fetch checks HTTP status, parses JSON, validates array and maps selected fields before output. The application's entry point is importUsers(). Baseline limitation, as stated in the workshop: Only the demo endpoint is allowed; internet availability matters.

Key building blocks: UrlFetchApp.fetch(); getResponseCode(); JSON.parse(); slice().

Practical use cases

Public data feeds and directory imports.

Prerequisites

  • What a URL is. JSON is explained in the walkthrough.
  • Interactive Learning Mode: a modern browser. Nothing else.
  • Real Workspace Build: a Google account.

Source data

Starter data: tab "Settings" (fictional)
URLLimit
https://jsonplaceholder.typicode.com/users3

Setup in your own Google account

  1. Download 04-external-api-data-importer.zip (Code.gs, starter.csv, README).
  2. In Google Drive, create a lesson folder and a new Google Sheets file inside it.
  3. Rename the first tab to exactly Settings, then File → Import → Upload starter.csv → Replace current sheet.
  4. Extensions → Apps Script. Replace Code.gs with the downloaded file. Save.
  5. Reload the spreadsheet, choose Workshop → Run application and authorize when asked.
  6. Check the result: Three user rows if endpoint is available; first user Leanne Graham.

Folder strategy: the repository's V6 code uses the folder that contains the spreadsheet. The deck mentions a Workshop Info cell B2; V6 never reads it. See the discrepancy log.

Complete source code (Code.gs)

From 04-external-api-data-importer at commit 4a26d919, SHA-256 e728881f0720. Unchanged.

// External API Data Importer
// Entry point: importUsers; source data stays intact unless explicitly noted.
function onOpen(){SpreadsheetApp.getUi().createMenu("Workshop").addItem("Run application","importUsers").addToUi();}
function importUsers(){
// Fetch and validate the complete response before changing the output.
const [url,limit]=input('Settings')[0]; if(url!=='https://jsonplaceholder.typicode.com/users')throw Error('Use the workshop endpoint');const res=UrlFetchApp.fetch(url,{muteHttpExceptions:true});if(res.getResponseCode()!==200)throw Error('HTTP '+res.getResponseCode());const data=JSON.parse(res.getContentText());if(!Array.isArray(data))throw Error('Expected array');const rows=data.slice(0,num(limit)).map(u=>[u.id,textField(u.name),textField(u.email),textField(u.address.city)]);output('Users',['ID','Name','Email','City'],rows);
}
function input(name) { const s=SpreadsheetApp.getActive().getSheetByName(name); if(!s) throw Error('Missing tab: '+name); return s.getDataRange().getValues().slice(1).filter(r=>r.some(v=>v!=='')); }
function output(name,headers,rows) { const ss=SpreadsheetApp.getActive(); const s=ss.getSheetByName(name)||ss.insertSheet(name); s.clearContents(); s.getRange(1,1,1,headers.length).setValues([headers]).setFontWeight('bold'); if(rows.length) s.getRange(2,1,rows.length,headers.length).setValues(rows.map(r=>r.map(v=>typeof v==='string' && /^[=+@-]/.test(v)?"'"+v:v))); s.setFrozenRows(1); return s; }
function num(v){if(v===''||!Number.isFinite(Number(v))) throw Error('Invalid number: '+v); return Number(v);}
function textField(v){if(typeof v!=='string'||!v.trim()) throw Error('Invalid AI text'); return v;}

How the code works

Beginner explanation

importUsers() asks a public test API for a list of users, checks that the answer is good, and writes the first few users into a Users tab. If anything is wrong it stops with a clear message and leaves the previous data alone.

Technical explanation

The URL is allow-listed to the workshop endpoint. UrlFetchApp.fetch with muteHttpExceptions:true returns non-2xx responses instead of throwing, so the code can check getResponseCode() itself. JSON.parse and Array.isArray validate the shape; textField() checks required strings. Only then does output() replace the Users tab. Note: textField() reports "Invalid AI text" here because the helper is shared with the AI lessons.

Slide excerpt

This is the excerpt shown on the workshop slide. It is a fragment and cannot run on its own.

function importUsers(){
// Fetch and validate the complete response before changing the output.
const [url,limit]=input('Settings')[0]; if(url!=='https://jsonplaceholder.typicode.com/users')throw Error('Use the workshop endpoint');const res=UrlFetchApp.fetch(url,{muteHttpExceptions:true});if(res.getResponseCode()!==200)throw Error('HTTP '+res.getResponseCode());const data=JSON.parse(res.getContentText());if(!Array.isArray(data))throw Error('Expected array');const rows=data.slice(0,num(limit)).map(u=>[u.id,textField(u.name),textField(u.email),textField(u.address.city)]);output('Users',['ID','Name','Email','City'],rows);
}

Common mistakes

  • Calling output() before validating, which wipes good data on a bad response.
  • Forgetting muteHttpExceptions and losing control of error messages.
  • Assuming nested fields like address.city always exist.

Run it and expected output

Choose Workshop → Run application (runs importUsers()). Expected: Three user rows if endpoint is available; first user Leanne Graham.

Original workshop exercise

Change limit from 3 to 2; expect two users if endpoint succeeds.

Troubleshooting and debugging

The server returns HTTP 500

The API is having a bad day. Switch the simulated endpoint to "HTTP 500" and run.

Fix: Retry when the service has recovered (set the simulated endpoint to Normal).

Validating the whole response before calling output() means a failed request never wipes the last good data.

Truncated JSON

The response was cut off mid-way. Switch the simulated endpoint to "Invalid JSON" and run.

Fix: Retry with a complete response; consider wrapping JSON.parse in try/catch with a clear message.

HTTP 200 does not guarantee usable data. Parse and validate before writing.

Extension activity: Record the last refresh

After a successful import, write a Refresh Log tab with the refresh time and the number of rows imported. Failed imports must not update it.

Acceptance checks:

  • Users still has 3 rows
  • Refresh Log shows 3 rows imported
  • A failed request does not create a Refresh Log

Original improvement idea from the workshop: Add configurable field mapping and a last-refresh timestamp.

Extension prompt
Update the existing app without removing working features. Add configurable field mapping and a last-refresh timestamp. Return complete updated files, explain changes and give regression tests.
Automation option: Schedule periodic refresh with HTTP error logging and a pinned spreadsheet ID. Keep this separate from the baseline exercise.

Automation considerations

Rerun-safe for the data (Users is replaced), but a schedule needs an explicit spreadsheet ID, error logging and awareness of the API's rate limits.

Workshop note: Schedule periodic refresh with HTTP error logging and a pinned spreadsheet ID.

Build prompt from the workshop

Act as a Google Apps Script tutor. Build a container-bound Sheets app for lesson 04: External API Data Importer. Input tab Settings, exact headers: URL, Limit. Create importUsers() using the URL and limit from Settings; fetch JSON, check HTTP status, validate array shape, write id/name/email/city to Users. Include an error message without deleting previous results on failure. Do not depend on Workshop Info or the Workshop Index. Provide complete copy-paste Code.gs (and HTML if required), exact setup/run steps, explain the main code blocks, and include a test matching this expected outcome: Three user rows if endpoint is available; first user Leanne Graham. Preserve starter data, use batch operations where appropriate, handle errors, and never send email or delete files. For AI lessons use the supplied callGemini helper, treat input as untrusted, and validate outputs.
Match the reference entry point importUsers and its output behavior. Reference: https://github.com/lsvekis/Google-Apps-Script-Workshop/tree/main/04-external-api-data-importer. Base version limitations: Only the demo endpoint is allowed; internet availability matters.

Knowledge check

  1. What does muteHttpExceptions: true change?

    1. fetch() returns 4xx/5xx responses instead of throwing, so the code can check the status
    2. It hides all errors from the log
    3. It retries failed requests
    Answer

    fetch() returns 4xx/5xx responses instead of throwing, so the code can check the status Correct: the code then throws its own clear "HTTP 500" message.

  2. The API returns {"users": []}. What happens?

    1. The run stops with "Expected array" and Users is unchanged
    2. Users is cleared
    3. Zero rows are imported successfully
    Answer

    The run stops with "Expected array" and Users is unchanged Correct: Array.isArray(data) is false for an object.

  3. Why is the URL compared against one exact address?

    1. To keep the workshop app from being pointed at arbitrary servers
    2. Because UrlFetchApp only supports one URL
    3. To make the request faster
    Answer

    To keep the workshop app from being pointed at arbitrary servers Correct: an allow-list limits where the script can send requests from your account.

  4. Users suddenly shows only two rows although Limit is 3 and there was no error. Most likely?

    1. Someone changed Settings!B2
    2. The API is down
    3. JSON.parse failed
    Answer

    Someone changed Settings!B2 Correct: slice(0, limit) follows the Settings value.

  5. Should a scheduled import keep running every hour during an API outage?

    1. It may run, but it must log failures and leave the last good data in place
    2. Yes, and clear the tab each time
    3. No API should ever be scheduled
    Answer

    It may run, but it must log failures and leave the last good data in place Correct: failures should be visible and non-destructive.

Five-minute presenter demonstration

Open the demo link (temporary workspace; saved learner work is not touched).

Opening hook: Raise your hand if you have ever done this by hand: Copying external API records manually wastes time. Let us make the spreadsheet do it.

  1. 0:00–0:45 — Problem and input. Show the Workspace view, Sheets service. Point at the Settings tab and its headers: URL, Limit. Say what goes in and what should come out.
    Narration: Copying external API records manually wastes time. Practical uses: Public data feeds and directory imports.
  2. 0:45–1:30 — Predict and run. Ask the room: Settings says Limit 3. How many users will be written to the Users tab? Click ▶ Run application (the same as Workshop → Run application). Open Trace to show each step the code took.
    Narration: Expected: Three user rows if endpoint is available; first user Leanne Graham.
  3. 1:30–3:00 — Explain the code. Click the Code tab. Select importUsers() in the function list; read what it reads, writes and calls. Switch Beginner / Technical as needed.
    Narration: importUsers() asks a public test API for a list of users, checks that the answer is good, and writes the first few users into a Users tab. If anything is wrong it stops with a clear message and leaves the previous data alone.
  4. 3:00–4:15 — Change one input and rerun. Back to the Workspace tab. Select the Settings tab, click cell B2, type 2 in the formula bar and press Enter. Click ▶ Run application again.
    Narration: Workshop challenge: Change limit from 3 to 2; expect two users if endpoint succeeds.
  5. 4:15–5:00 — Verify and discuss automation. Click Check result. Discuss: Rerun-safe for the data (Users is replaced), but a schedule needs an explicit spreadsheet ID, error logging and awareness of the API's rate limits.
    Narration: Baseline limitation: Only the demo endpoint is allowed; internet availability matters.

Closing takeaway: Fetch checks HTTP status, parses JSON, validates array and maps selected fields before output.

Related resources