【问题标题】:Calling API in R (httr package)在 R 中调用 API(httr 包)
【发布时间】:2017-08-16 20:31:27
【问题描述】:

希望您能帮助我,我不是集成专家 :)

有一个称为社交面包师的系统(文档:https://api.socialbakers.com),我尝试在其中获取一些数据。我有一个令牌,一个秘密,我认为我做的第一部分是正确的。

我只是想用这个 sn-p 连接:

library(httr)

req <- GET("https://api.socialbakers.com/0/facebook/profiles", 
       authenticate("token", "secret", type = "basic"))
stop_for_status(req)
content(req)

这非常有效。我有一个 JSON 响应,可以将其解析为表格。 我的问题是关于这样的另一个 URL:

library(httr)

req <- GET("https://api.socialbakers.com/0/facebook/metrics", 
       authenticate("token", "secret", type = "basic"))
stop_for_status(req)
content(req)

相同的代码,不再起作用,返回

代码 405 HTTP 方法无效

我不确定我是否做得对,文档的某些部分说我必须在标题上使用 base64,但为什么在第一部分工作?一些建议将不胜感激:)

编辑:

已解决:在这种情况下,与 API 交互的正确方法是使用 POST 方法将参数发送到服务。

使用了以下sn-p。

library(httr)
library(RCurl)
library(jsonlite)

doc <- POST("https://api.socialbakers.com/0/facebook/metrics",
        authenticate("user",
                     "pass",
                     type = "basic"), 
        body = list(
          date_start = "2016-01-11",
          date_end = "2016-01-12",
          profiles = c("12345", "123456"),
          metrics = c("fans_count_lifetime", "fans_change"))
        , encode = "json")
stop_for_status(doc)
content(doc)

谢谢。

【问题讨论】:

  • 根据您提供的链接中的文档,对指标的请求需要参数。他们有一个example request(右侧)。

标签: json r api header httr


【解决方案1】:

在这种情况下,与 API 交互的正确方法是使用 POST 方法将参数发送到服务。

使用了以下sn-p。

library(httr)
library(RCurl)
library(jsonlite)

doc <- POST("https://api.socialbakers.com/0/facebook/metrics",
    authenticate("user",
                 "pass",
                 type = "basic"), 
    body = list(
      date_start = "2016-01-11",
      date_end = "2016-01-12",
      profiles = c("12345", "123456"),
      metrics = c("fans_count_lifetime", "fans_change"))
    , encode = "json")
stop_for_status(doc)
content(doc)enter code here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多