简体   繁体   English

在R中调用API(httr包)

[英]Calling API in R (httr package)

Hope you can help me, I am not an expert on integrations :) 希望您能帮助我,我不是集成专家:)

There is a system called social bakers (doc: https://api.socialbakers.com ) where I try to fetch some data. 有一个名为“社交面包师”的系统(文档: https//api.socialbakers.com ),我尝试在其中获取一些数据。 I have a token, a secret and I think I am doing the first part right. 我有一个记号,一个秘密,我想我在做第一部分。

I am just trying to connect using this snippet: 我只是想使用此代码段进行连接:

library(httr)

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

This works perfectly. 这很完美。 I have a JSON response which I can parse into a table. 我有一个JSON响应,可以将其解析为一个表。 My question is about another URL like this: 我的问题是关于这样的另一个URL:

library(httr)

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

The same code, doesn't work anymore, returning 相同的代码不再起作用,返回

code 405 HTTP Method Invalid 代码405 HTTP方法无效

I am not sure if I am doing right, some part of the doc says I have to use base64 on the header, but why is working in the first part? 我不确定我是否做得正确,文档的某些部分说我必须在标头上使用base64,但是为什么在第一部分中工作? Some advice will be really appreciated :) 一些建议将不胜感激:)

EDIT: 编辑:

SOLVED: In that case, the correct method to interact with the API is using the POST method to send the parameters to the service. 已解决:在那种情况下,与API交互的正确方法是使用POST方法将参数发送到服务。

The following snippet was used. 使用了以下代码段。

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)

Thanks. 谢谢。

In that case, the correct method to interact with the API is using the POST method to send the parameters to the service. 在这种情况下,与API交互的正确方法是使用POST方法将参数发送到服务。

The following snippet was used. 使用了以下代码段。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM