You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言API分页循环缺失第一页数据问题求助

问题:API分页获取数据缺失第一页内容

调用API时每页最多返回100行数据,因此用while循环获取所有分页数据,但最终结果里缺少第一页数据。第一页数据存在apidata <- apiresponse$data$data中,但未被加入最终的data列表,当前代码如下:

# Required packages
library(httr)
library(jsonlite)
library(data.table)
library(dplyr)
library(lubridate)
library(stringr)
library(keyring) 


url = "https://app.website.com/api/account/v1/account/sales/export/default-extended?period_filter_on=updated_date&period=this_month"

request <- GET(url, add_headers(Authorization = paste(key_get(service = "Website"))))
this.raw.content <- rawToChar(request$content)
apiresponse <- jsonlite::fromJSON(this.raw.content)
next_url <- apiresponse$data$next_page_url
apidata <- apiresponse$data$data

data <- list()
i <- 1

while(!is.null(next_url)) {
  request <- GET(apiresponse$data$next_page_url,
             add_headers(Authorization = paste(key_get(service = "Website"))))
  this.raw.content <- rawToChar(request$content)
apiresponse <- jsonlite::fromJSON(this.raw.content)
next_url <- apiresponse$data$next_page_url
temp <- apiresponse$data$data
rownames(temp) <- NULL
data[[i]] <- temp
i <- i + 1
}


result <- do.call(rbind, data)
解决方案

问题核心是第一页数据未被加入data列表,循环只处理了从第二页开始的内容。只需在进入循环前,把第一页的apidata添加到data里,并调整计数器的初始值即可修复。

修改后的完整代码

# Required packages
library(httr)
library(jsonlite)
library(data.table)
library(dplyr)
library(lubridate)
library(stringr)
library(keyring) 


url = "https://app.website.com/api/account/v1/account/sales/export/default-extended?period_filter_on=updated_date&period=this_month"

request <- GET(url, add_headers(Authorization = paste(key_get(service = "Website"))))
this.raw.content <- rawToChar(request$content)
apiresponse <- jsonlite::fromJSON(this.raw.content)
next_url <- apiresponse$data$next_page_url
apidata <- apiresponse$data$data

# 初始化列表时直接加入第一页数据
data <- list(apidata)
# 计数器从2开始,第一页已占列表第1位
i <- 2

while(!is.null(next_url)) {
  request <- GET(apiresponse$data$next_page_url,
             add_headers(Authorization = paste(key_get(service = "Website"))))
  this.raw.content <- rawToChar(request$content)
apiresponse <- jsonlite::fromJSON(this.raw.content)
next_url <- apiresponse$data$next_page_url
temp <- apiresponse$data$data
rownames(temp) <- NULL
data[[i]] <- temp
i <- i + 1
}


result <- do.call(rbind, data)

另一种等价写法

如果习惯先初始化空列表,也可以手动先把第一页数据加入列表:

data <- list()
# 先添加第一页数据到列表
data[[1]] <- apidata
i <- 2

# 后续循环逻辑保持不变
while(!is.null(next_url)) {
  # ... 循环内代码与原代码一致
}

两种写法都能确保第一页数据被包含到最终的result中。

内容的提问来源于stack exchange,提问作者Tinus Brand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 01:53:12