如何通过Google Apps Script实现WhipAround API与Google Sheets连接?
解决WhipAround API与Google Sheets的连接问题
问题背景
尝试将WhipAround API连接到Google Sheets时遇到故障,现有可用的Fetch请求代码如下:
const options = { method: 'GET', headers: { accept: 'application/json', 'X-API-KEY': 'MyKey' } }; fetch('https://api.whip-around.com/api/public/v4/work-orders?limit=20&page=1', options) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error(err));
自行编写的Google Apps Script代码无法正常运行:
function fetchDataFromAPI() { var apiUrl = 'https://api.whip-around.com/api/public/v4/work-orders'; var headers = { 'Authorization': 'Bearer MyKey' }; var options = { 'headers': headers }; var response = UrlFetchApp.fetch(apiUrl, options); var responseData = JSON.parse(response.getContentText()); // Now you can manipulate the API data and update your Google Sheet var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var numRows = responseData.length; var numCols = responseData[0].length; sheet.getRange(1, 1, numRows, numCols).setValues(responseData); }
故障截图:
原代码问题分析
- 请求头错误:WhipAround API使用
X-API-KEY作为身份验证头,而非Authorization: Bearer,这会导致权限验证失败。 - API参数缺失:原Fetch请求包含
limit=20&page=1分页参数,而GAS代码中未添加,可能导致返回数据不符合预期或接口返回错误。 - 数据结构处理错误:WhipAround API返回的是包含
data字段的JSON对象(而非直接的数组),且每个工单是键值对对象,无法直接用setValues写入表格,需要先转换为二维数组格式。
修正后的Google Apps Script代码
function fetchWhipAroundData() { // 配置API参数和密钥 const apiKey = '你的实际API密钥'; const apiUrl = 'https://api.whip-around.com/api/public/v4/work-orders?limit=20&page=1'; // 设置请求头,与Fetch代码保持一致 const options = { method: 'GET', headers: { 'accept': 'application/json', 'X-API-KEY': apiKey } }; try { // 发送API请求 const response = UrlFetchApp.fetch(apiUrl, options); const responseJson = JSON.parse(response.getContentText()); // 提取工单数据(API返回的data字段是工单数组) const workOrders = responseJson.data; if (!workOrders || workOrders.length === 0) { SpreadsheetApp.getUi().alert('未获取到工单数据'); return; } // 转换数据为二维数组:先提取表头,再提取每行数据 const headers = Object.keys(workOrders[0]); const rows = workOrders.map(order => headers.map(header => order[header])); // 将表头和行数据合并 const sheetData = [headers, ...rows]; // 写入Google Sheets const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); sheet.clearContents(); // 清空原有内容(可选) sheet.getRange(1, 1, sheetData.length, sheetData[0].length).setValues(sheetData); SpreadsheetApp.getUi().alert('数据导入成功'); } catch (err) { SpreadsheetApp.getUi().alert(`请求失败:${err.message}`); console.error(err); } }
注意事项
- 替换代码中的
你的实际API密钥为WhipAround平台提供的有效API Key。 - 如果需要获取更多数据,可修改
limit参数或实现分页循环(遍历page参数直到返回数据为空)。 - 首次运行时需授权脚本访问Google Sheets和外部API权限。
- 若仍有错误,可查看脚本编辑器的日志(
查看>日志)获取详细错误信息。
内容的提问来源于stack exchange,提问作者Luke Gruber
相关产品推荐
相关产品推荐

