在 Google Apps 脚本中使用 smartsheet API 添加行

Adding rows with smartsheet API in Google Apps Script

我在 中遇到了与 user:itsallgood 相同的困难--当我提交以下添加行的请求时出现以下错误。

{"errorCode":1008,"message":"Unable to parse request. The following error occurred: Request body must be either a JSON object or JSON array."}

我相信数据格式正确,并且我已经验证它在 jsonformatter.curiousconcept.com 有效 JSON。

var params = {  
   "headers":{  
      "authorization":"Bearer <<removed for public posting>>"
   },
   "contentType":"application/json",
   "method":"PUT",
   "body":[  
      {  
         "toBottom":true,
         "cells":[  
            {  
               "columnId":4209581015492484,
               "value":"New row"
            }
         ]
      }
   ]
}
var response = UrlFetchApp.fetch("https://api.smartsheet.com/2.0/sheets/<<sheet key removed>>/rows", params)

提供给 itsallgood 的答案是,问题是由于 API 1.1 端点的错误,2.0 将解决它。但是,我使用的是 API 2.0 端点,但仍然出现错误。

如果有人能帮忙解开这个谜语,我将不胜感激!

使用 Postman, Chrome Advanced Rest Client, or cUrl 等交互式工具进行测试要容易得多。我不确定您的脚本实际上通过网络发送了什么。

几个观察结果

UrlFetch docs 示例包括从 JS 对象到 JSON 字符串的显式转换:

var data = { ... }

var params = {
    'method' : 'post',
    'contentType': 'application/json',
    // Convert the JavaScript object to a JSON string.
    'payload' : JSON.stringify(data)
};

另请注意,在您设置 params.body

时,示例设置 params.payload

此外,PUT /sheets/{sheetId}/rows 用于更新一个或多个 现有 行。因此,有效负载中的每个行对象都需要一个行 ID。请参阅 docs.
中的示例 或者,您可以 POST 一个新行。

这是一个完整的例子:

function addRow(){
var url ="https://api.smartsheet.com/2.0/sheets/5670346721388420/rows";

var data ={
        "toBottom": true,
        "cells": [
            {
                "value": "New data",
                "columnId": 5759377954105220
            }
        ]
    };

var options ={
        "headers": {
            "authorization": "Bearer ll352u9jujauoqz4fstvsae05"
        },
        "method": "post",
        "contentType": "application/json",
        "payload": JSON.stringify(data)
    };
Logger.log("About to call: " + url);

var response = UrlFetchApp.fetch(url, options);

Logger.log("Response: " + response);
}