External API Data Importer
Copying external API records manually wastes time.
What this teaches
Import public JSON into a spreadsheet. Public data feeds and directory imports.
Start without an account in the local application. Read/edit the input, predict a result, run the current source and verify output. A local document preview is not a real Google Doc; a fixture is not a live model response.
Input and expected result
Input tab: Settings. Entry function: importUsers().
| URL | Limit |
|---|---|
| https://jsonplaceholder.typicode.com/users | 3 |
Expected baseline: Three user rows if endpoint is available; first user Leanne Graham.
Exact Workspace setup
- Download and unzip this project. Use one separate bound script per lesson.
- Create a dedicated Drive folder. Create a native Google Sheet inside it, and import starter.csv into a tab named Settings. Check the exact headers above.
- Open the Sheet → Extensions → Apps Script. Paste finished Code.gs into the script editor. Save.
- Choose importUsers in the function selector → Run. Review actual requested permissions. Reload the Sheet for the Workshop menu.
- Compare output with the baseline above. Check generated documents/drafts manually. No email should be sent.
- Perform the original challenge, investigate a failure and test duplicate/partial runs before scheduling. Do not install a trigger just because one manual run succeeded.
Understand the implementation
Fetch checks HTTP status, parses JSON, validates array and maps selected fields before output.
Key operations: UrlFetchApp.fetch(); getResponseCode(); JSON.parse(); slice()
Focused source spotlight
This is an excerpt, not a standalone script. The complete implementation follows.
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);
}Complete Code.gs
// 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;}
Four guided activities
Discover and run
Copying external API records manually wastes time.
- Inspect the editable Settings table. The starter has 1 records.
- Write your predicted result in Prediction. Click Run application.
- Compare Output with: Three user rows if endpoint is available; first user Leanne Graham.
- Click Verify baseline; explain one result in Notes.
Expected: Three user rows if endpoint is available; first user Leanne Graham.
Understand and modify
Change limit from 3 to 2; expect two users if endpoint succeeds.
- Open Source and read importUsers. Select the entry function in the walkthrough.
- Return to Application. Click Prepare original challenge to create a separate challenge starting state.
- For AI projects inspect the revised recorded fixture: this is supplied response data, not newly generated AI.
- Run application and use Verify challenge; approval/sidebar projects show extra required steps.
Expected: Change limit from 3 to 2; expect two users if endpoint succeeds.
Investigate and repair
HTTP failure
- Save a snapshot if you want to keep your experiment.
- Click Inject investigation. Use response status 429 in Recorded response. Run and inspect the request trace.
- Run application and inspect Output and Execution trace. Some investigations produce wrong/stale content rather than exceptions.
- Repair it: Restore status 200; do not add blind retries. Run again and explain the root cause.
Expected: The reference checks HTTP status before parsing JSON.
Extend and automate
Add configurable field mapping and a last-refresh timestamp.
- Open Prompts. Select Extend and adapt the requirement to your goal.
- Build the feature in Source or export the complete project to Apps Script.
- Retest baseline and original challenge before considering scheduling.
- Use Resources → Automation readiness. Schedule periodic refresh with HTTP error logging and a pinned spreadsheet ID.
Expected: The baseline still works; independent extension checks are designed and reviewed by you.
Original exercise
Change limit from 3 to 2; expect two users if endpoint succeeds.
Debugging and troubleshooting
HTTP failure
Use response status 429 in Recorded response. Run and inspect the request trace.
Hint 1
Check the exact input/response contract and identify the affected field.
Hint 2
Fetch checks HTTP status, parses JSON, validates array and maps selected fields before output.
Hint 3 and repair
Restore status 200; do not add blind retries.
The reference checks HTTP status before parsing JSON.
Missing tab: check its exact name. Missing document: ensure unique native companion Docs share the Sheet’s dedicated folder. Authorization failure: review source and contact your administrator. Recorded response exhausted: add a new explicit fixture; no live AI is running. Invalid JSON: repair syntax before validating schema. Valid but unsupported content: compare each claim with source records.
Build prompt
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.
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.
Knowledge check and answer key
- Which input tab does importUsers read?
Answer
Settings
- Which function starts the original application?
Answer
importUsers
- What is the baseline output you must verify?
Answer
Three user rows if endpoint is available; first user Leanne Graham.
- Does this project need runtime Gemini in the real Workspace baseline?
Answer
No; Gemini can help during development only.
- What limitation matters before scheduling?
Answer
Only the demo endpoint is allowed; internet availability matters.
Safe automation
Schedule periodic refresh with HTTP error logging and a pinned spreadsheet ID.
Only the demo endpoint is allowed; internet availability matters.
Reflect and extend
Explain the transformation using one actual input row. Which incorrect value could still pass structural validation? What happens if the function runs twice or fails after creating one output? Write your explanation before building this extension: Add configurable field mapping and a last-refresh timestamp.
Source alignment
Physical slide 23; printed sequence 14 of 48. Reference source SHA-256 e728881f0720c1150cad3f1f66e1cda5eaf4ceacbb08daad90a67599d73f8af6.
Slide notes use Workshop Info B2. Verified repository resolves the active spreadsheet parent folder; this build follows the repository. Keep companion files in that dedicated lesson folder.
Pinned repository reference · Full source manifest
Five-minute presenter demonstration
0:00–0:45
Action: Open Input. Read Settings headers and first row.
Copying external API records manually wastes time. This application is useful for Public data feeds and directory imports. We will run the verified reference code against fictional data.
0:45–1:30
Action: Ask for predictions. Click Run application, then Verify baseline.
Our baseline is Three user rows if endpoint is available; first user Leanne Graham. The browser displays local results. It has not connected to Google or a model.
1:30–3:00
Action: Open Source. Select importUsers in the code walkthrough.
Fetch checks HTTP status, parses JSON, validates array and maps selected fields before output. The complete code is available to edit and download. The excerpt is not a standalone script.
3:00–4:15
Action: Click Prepare original challenge, inspect the changed inputs, and Run application. Complete extra review/sidebar steps if listed.
Change limit from 3 to 2; expect two users if endpoint succeeds. For AI lessons we edit a recorded response as well as source data. That response must be checked, not trusted.
4:15–5:00
Action: Click Verify challenge. Open Guide and read Automation considerations.
The important limitation is: Only the demo endpoint is allowed; internet availability matters. Before scheduling: Schedule periodic refresh with HTTP error logging and a pinned spreadsheet ID. Explain the result yourself before moving on.