【问题标题】:API Data Extraction with Tidyverse使用 Tidyverse 进行 API 数据提取
【发布时间】:2018-03-28 05:45:04
【问题描述】:

我的最终目标是为我的公司建立一些报告。我们使用了一些 SaaS 工具,包括用于时间跟踪的 Harvest(示例如下)。我打算围绕 API 编写包装器,以从每个 API 中提取一些数据集,但我想以一种易于阅读/维护的方式来做(即,我想尽可能坚持使用 tidyverse)。

下面的代码提取我需要的时间表数据并将其转换为数据框。但是,API 被分页到每次返回 100 行。 API 返回我的当前页面和页面总数,因此编写一个 while 循环很简单。

我的问题:有没有办法在下面的管道语句中执行 while 循环(例如 while 'page'

httr::modify_url(url="https://api.harvestapp.com",path="v2/time_entries") %>% 
      purrr::map(~httr::GET(.,httr::add_headers("Harvest-Account-ID" = user,Authorization = my_key,"User-Agent" = my_email))) %>% 
      purrr::map(~httr::content(., as="text", encoding = "UTF-8")) %>% 
      purrr::map(~jsonlite::fromJSON(., flatten = T)) %>% 
      purrr::map('time_entries')

非常感谢任何建议或参考,谢谢!

【问题讨论】:

  • It looks like total_pages is within the response,所以你可以在没有while的情况下迭代到那个。
  • @alistaire 谢谢,是的,total_pages 在响应中,但是我怎样才能不一会儿就迭代到那个呢?抱歉,这可能很明显,我只是想多了....
  • map(seq(response$total_pages), ...)
  • @alistaire 非常感谢!多亏了你的帮助,我才能把它缝合起来。

标签: r api tidyverse purrr httr


【解决方案1】:

感谢@alistaire,我能够为任何对未来感兴趣的人找到答案。这可能会大大简化,所以请随时添加。

report <- 'v2/time_entries'
httr::modify_url(url="https://api.harvestapp.com",path=report) %>% 
  purrr::map(~httr::GET(.,httr::add_headers("Harvest-Account-ID" = user,Authorization = my_key,"User-Agent" = my_email))) %>% 
  purrr::map(~httr::content(., as="text", encoding = "UTF-8")) %>% 
  purrr::map(~jsonlite::fromJSON(., flatten = T)) %>% 
  purrr::map("total_pages") %>% 
  unlist %>% 
  seq(.) %>% 
  purrr::map(~httr::modify_url(url="https://api.harvestapp.com",path=paste0("v2/time_entries?page=",.))) %>% 
  unlist %>% 
  purrr::map(~httr::GET(.,httr::add_headers("Harvest-Account-ID" = user,Authorization = my_key,"User-Agent" = my_email))) %>% 
  purrr::map(~httr::content(., as="text", encoding = "UTF-8")) %>% 
  purrr::map(~jsonlite::fromJSON(., flatten = T)) %>% 
  purrr::map("time_entries") %>% 
  do.call("rbind", .)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    相关资源
    最近更新 更多