【问题标题】:Pagination response from API in Loop for R来自 API in Loop for R 的分页响应
【发布时间】:2021-05-24 10:56:29
【问题描述】:

我正在开发一个 API,其中响应最多限制为 100 行,但在它返回的列表中,它会提供到下一页的链接。

例子:

> apiresponse$paging
$`next`
[1] "https://workable.com/spi/v3/accounts/xx-xx-xx-xx/jobs?limit=100&since_id=1233xxb"

所以,要从下一页获取数据,我必须添加上面提到的 URL 来调用 API。

API 代码

url = "https://workable.com/spi/v3/accounts/xx-xx-xx-xx/jobs?limit=100"
key = "xxxxxxxxxxxxx"

# OPTION 1
x <- GET(url, add_headers(Authorization = paste("Bearer", key, sep = " ")))

this.raw.content <- rawToChar(x$content)

apiresponse <- jsonlite::fromJSON(this.raw.content)


apiresponse$paging
apidata <- apiresponse$jobs

要求 我可能想要一个函数,其中 NEXT URL 会自动进入 API 调用循环,直到所有数据都在这里。

【问题讨论】:

    标签: r function api dplyr


    【解决方案1】:

    您可以尝试使用while 循环并捕获数据,直到next 不为空。

    url = "https://workable.com/spi/v3/accounts/xx-xx-xx-xx/jobs?limit=100"
    key = "xxxxxxxxxxxxx"
    # OPTION 1
    x <- GET(url, add_headers(Authorization = paste("Bearer", key, sep = " ")))
    this.raw.content <- rawToChar(x$content)
    apiresponse <- jsonlite::fromJSON(this.raw.content)
    next_url <- apiresponse$paging$`next`
    apidata <- apiresponse$jobs
    
    data <- list()
    i <- 1
    
    while(!is.null(next_url)) {
      x <- GET(apiresponse$paging$`next`, 
               add_headers(Authorization = paste("Bearer", key, sep = " ")))
      this.raw.content <- rawToChar(x$content)
      apiresponse <- jsonlite::fromJSON(this.raw.content)
      next_url <- apiresponse$paging$`next`
      temp <- apiresponse$jobs
      rownames(temp) <- NULL
      data[[i]] <- temp
      i <- i + 1
    }
    
    result <- do.call(rbind, data)
    

    【讨论】:

    • 嗨@ronakshah,它似乎将输出作为列表提供,而理想情况下我想要一个rbinded data.frame。
    • 是的,我最后添加了result &lt;- do.call(rbind, data) 以获得一个组合数据帧。
    • 我明白了,似乎正在发生的是,重复的行名,因此它返回一个错误Error in `.rowNamesDF&lt;-`(x, value = value) : duplicate 'row.names' are not allowed
    • 好吧,如果没有工作,就很难提供帮助,因为我们无法确定答案是否有效,但可能会尝试从数据中删除行名。查看更新的答案。
    • 你的代码基本上可以工作,我会找到解决这个行名问题的方法。谢谢
    猜你喜欢
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 2016-01-17
    相关资源
    最近更新 更多