正确的 next_req() 使用 httr2 对 API 请求进行分页?

问题描述 投票:0回答:1

我想使用 httr2 的 req_perform_iterative 函数迭代调用分页 API,其中响应提供下一个要请求的 url。

但是,我似乎无法正确形成

next_req()
参数或使用迭代助手,例如
iterate_with_cursor()
,并且文档中的示例很简单。就我而言,我需要使用下一个 url,而不是偏移页码,因为这是我调用的 API 的分页系统。

有人可以帮我构建一个正确的

next_req()
函数吗?

我们可以使用rick and morty api作为例子:

library(httr2)

# request a single page
req <- request("https://rickandmortyapi.com/api/character?page=1") |>
  req_perform() |>
  resp_body_json()

# return the url for the next page
next_url <- req$info$"next"

如何将其转换为可返回多个页面的工作

req_perform_iterative()
函数?谢谢!

r pagination httr2
1个回答
0
投票

对于这个特定的示例(响应正文中下一页的完整 URL),构建一个新的迭代助手可能更容易,我们可以将现有的一个作为模板:

library(httr2)

# existing iteration helper, follows url found in the Link header:
iterate_with_link_url()
#> function (resp, req) 
#> {
#>     url <- resp_link_url(resp, rel)
#>     if (!is.null(url)) {
#>         req %>% req_url(url)
#>     }
#> }

# custom helper based on iterate_with_link_url(),
# follow next url from response body
iterate_with_body_info_next <- function(resp, req) {
  url <- resp_body_json(resp)$info$`next`
  if (!is.null(url)) {
    req %>% req_url(url)
  }
}

resps <- 
  request("https://rickandmortyapi.com/api/character") |> 
  req_perform_iterative(
    next_req = iterate_with_body_info_next,
    max_reqs = 3
)
resps
#> [[1]]
#> <httr2_response>
#> GET https://rickandmortyapi.com/api/character
#> Status: 200 OK
#> Content-Type: application/json
#> Body: In memory (19496 bytes)
#> 
#> [[2]]
#> <httr2_response>
#> GET https://rickandmortyapi.com/api/character?page=2
#> Status: 200 OK
#> Content-Type: application/json
#> Body: In memory (10380 bytes)
#> 
#> [[3]]
#> <httr2_response>
#> GET https://rickandmortyapi.com/api/character?page=3
#> Status: 200 OK
#> Content-Type: application/json
#> Body: In memory (9723 bytes)

# info object from the 1st request body
str(resp_body_json(resps[[1]])$info)
#> List of 4
#>  $ count: int 826
#>  $ pages: int 42
#>  $ next : chr "https://rickandmortyapi.com/api/character?page=2"
#>  $ prev : NULL

创建于 2024 年 10 月 18 日,使用 reprex v2.1.1

© www.soinside.com 2019 - 2024. All rights reserved.