使用R中的httr包获取更多对象

时间:2016-03-11 17:05:05

标签: r get httr

我使用httr包来从Data API获取数据:

request3 <- GET(url = "https://api.data-api.io/xxxxx/", add_headers('x-dataapi-key' = "xxxxx"), query = list(oib = "18527887472"))

如何在一行代码中获取更多对象?让我们说我有一个向量:

oibreq <- c("18527887472", "92680516748", "00045103869")

我想为这3&#34;查询&#34;获取对象。很长的路要走3次GET功能:

 request1 <- GET(url = "https://api.data-api.io/xxxx", add_headers('x-dataapi-key' = "xxxx"), query = list(oib = "18527887472"))
request2 <- GET(url = "https://api.data-api.io/v1/eoglasna/", add_headers('x-dataapi-key' = "xxxx"), query = list(oib = "00045103869"))
request2 <- GET(url = "https://api.data-api.io/v1/eoglasna/", add_headers('x-dataapi-key' = "xxxx"), query = list(oib = "92680516748"))

有没有更快的方法呢?如果我有100个oibreq元素,那就是问题。

2 个答案:

答案 0 :(得分:0)

您可以编写自己的函数,然后通过lapply()将对象ID向量传递给函数:

my_get <- function(object) {
  GET(url = "https://api.data-api.io/v1/eoglasna/", 
      add_headers('x-dataapi-key' = "xxxx"), 
      query = list(oib = object))
}
lapply(oibreq, my_get)

答案 1 :(得分:0)

我找到了问题的答案:

req <- list()
my_get <- for (i in 1:length(oibreq)) {
  reqOP <- rbind(fromJSON(toJSON(content(GET(url = "https://api.data-api.io/v1/eoglasna/", 
                              add_headers('x-dataapi-key' = "xxx"), 
                              query = list(oib = oibreq[i])), type = "application/json"), null = "null"), flatten = TRUE))
  req[[i]] <- reqOP
}
big_data <- do.call(rbind, req)