使用 rcurl 连接到 BI 工具的 REST API

Connecting to BI tool's REST API using rcurl

我正在尝试从 R 中直接连接到 BI 工具的 API。API 文档列出了以下用于获取身份验证令牌的 curl 命令:

curl -X POST -H "Content-Type: application/json" -d
                 '{
                    "email": "your@email.com",
                    "password": "your_password"
                 }'
https://app.datorama.com/services/auth/authenticate

此外,下面是可用于查询数据的JSON查询示例:

{
"brandId": "9999",
"dateRange": "CUSTOM",
"startDate": "2016-01-01",
"endDate": "2016-12-31",
"measurements": [
    {
        "name": "Impressions"
    }
],
"dimensions": [
    "Month"
],
"groupDimensionFilters": [],
"stringDimensionFilters": [],
"stringDimensionFiltersOperator": "AND",
"numberDimensionFiltersOperator": "AND",
"numberMeasurementFilter": [],
"sortBy": "Month",
"sortOrder": "DESC",
"topResults": "50",
"groupOthers": true,
"topPerDimension": true,
"totalDimensions": [] 
}

我正在尝试 1) 将上面的 curl 命令翻译成 R 以获得所需的身份验证令牌,以及 2) 通过上面的 JSON 脚本查询数据。

到目前为止,我已尝试使用 httr 库,如下所示:

library(httr)
r <- POST('https://app.datorama.com/services/auth/authenticate',  
          body = list(
              brandId = "9999",
              dateRange = "CUSTOM",
              measurements = list(name="Impressions"),
              dimensions = list(name="Month"),
              startDate = "2016-01-01",
              endDate = "2016-12-31"
          ), 
          encode = "json",
          authenticate("username", "password"))

无果。

API 文档在受密码保护的页面后面,因此我无法 link 它。如果需要其他信息,请告诉我。

我无权访问他们的 API,如果他们有免费套餐,我可能会为此服务编写一个小的包装器 pkg。话虽如此,

curl -X POST \
     -H "Content-Type: application/json" \
     -d '{ "email": "your@email.com",
           "password": "your_password" }'

转换为:

library(httr)

res <- POST("https://app.datorama.com/services/auth/authenticate",
            body=list(email="your@email.com", 
                      password="your_password"),
            encode="json")

他们也没有免费在线应用程序 API 文档,但我假设它会发回 JSON 某种类型的 authorization_token 响应并进行编码字符串。

然后你——很可能——需要通过 every 随后的 API 调用传递该结果(并且可能有一个超时,初始身份验证将需要重新升级)。

authenticate()用于HTTP basic auth,不适用于这种in-API JSON/REST auth.

除了使用令牌身份验证之外,您的实际 API 调用看起来还不错。

hrbrmstr 完全正确!您应该生成两个 api 调用,第一个是对用户进行身份验证,第二个是查询数据。

下面是使用 R 中的 Datorama 查询 API 的完整示例。如有任何其他问题,请随时联系 Datorama 支持。

library(httr)

res <- POST("https://app.datorama.com/services/auth/authenticate",
            body=list(email="your@email.com", 
                      password="your_password"),
            encode="json")

token <- content(res)$token

res_query <- POST(paste("https://app.datorama.com/services/query/execQuery?token=",token, sep=""),
        body = list(
              brandId = "9999",
              dateRange = "CUSTOM",
              measurements = list(list(name = "Impressions")),
              dimensions = list("Month"),
              startDate = "2016-01-01",
              endDate = "2016-12-31"
          ), 
          encode = "json")

cat(content(res_query, "text"), "\n")