将日期参数传递给 REST API 调用 - 使用 R-

Passing Date parameters into REST API call - Using R-

尝试从 REST API 中提取一些数据,但无法将其作为日期参数正确传递到字符串中。使用 sprintf 我成功地传递了搜索词和网站,但是 discoverDate 没有运气。

https://newsriver.io 是有问题的 API

Function to grab data by one search term and one website

get_newsriver_content <- function(searcht,website,api_key){
url <- sprintf('https://api.newsriver.io/v2/search?query=text%%3A%s%%20OR%%20website.domainName%%3A%s%%20OR%%20language%%3AEN&sortBy=_score&sortOrder=DESC&limit=100',searcht, website)
news_get<- GET(url, add_headers(Authorization = paste(api_key, sep = "")))
news_txt <- content(news_get, as = "text", encoding = "UTF-8") 
news_df <- fromJSON(news_txt)
news_df$discoverDate <- as.Date(news_df$discoverDate)
news_df
}

问题已更新 - 我还想根据日期向量进行多次 API 调用。

这是我解决问题的方法

这真的是一个两步问题

  1. 弄清楚如何正确编码要插入到 Curl 调用中的查询
  2. 创建一个函数,该函数根据日期向量进行 API 调用并将其附加到数据框。

这是我的做法。

library(tidyverse)
library(jsonlite)
library(urltools)
library(httr)

# Function For Pulling by Date  
get_newsriver_bydate <- function(query, date_v){

#Being Kind to the free API - Shout out to Elia at Newsriver who has been ever patient
pb$tick()$print()
Sys.sleep(sample(seq(0.5, 2.5, 0.5), 1))

#This is where is used the URL encode package as suggested by quartin
url_base <- "https://api.newsriver.io/v2/search"
create_curl_call <- url_base %>% 
param_set("query",url_encode(query)) %>% 
param_set("sortBy", "_score") %>% 
param_set("sortOrder", "DESC") %>% 
param_set("limit", "100") 

#I had most of this before however I changed my output to a tibble
#more versatile to work with 

get_curl <- GET(create_curl_call, add_headers(Authorization = paste(api_key, sep = "")))
curl_to_json <- content(get_curl, as = "text", encoding = "UTF-8")
news_df <- fromJSON(curl_to_json, flatten = TRUE)
news_df$discoverDate <- as.Date(news_df$discoverDate)
as.tibble(news_df)
}

# Set Configration and Set API key
set_config(config(ssl_verifypeer = 0L))
api_key <- "mykey"

#Set my vector of Dates
dates1 <- seq(as.Date("2017-09-01"), as.Date("2017-10-01"), by = "days")

#Set up my progress bar
pb <- progress_estimated(length(dates1))

#Sprintf my query into a vector of queries based on date
query <- sprintf('text:"Canada" AND text:"Rocks" AND language:EN AND discoverDate:[%s TO %s]',dates1, dates1)

 #Run the query and be patient
news_df <- map_df(query, get_newsriver_bydate, .id = "query")

所以对于我的研究方法以及我是如何解决这两个问题的

  1. Quartin 给了我一个查找 urltools 包的建议 https://cran.rstudio.com/web/packages/urltools/index.html - 这个包可以帮助你编码和解码你的 URL 和其他各种快速和矢量化的功能。接下来我的问题是让我的查询在这里正确,我只是查阅了 API 文档,我建议任何试图从 API 中提取的文档。可能听起来很简单,但在 post 提出我的问题

  2. 之前我没有完整阅读它
  3. 创建函数我使用了一些以前的答案来帮助构建它但是下面的 post 帮助最大

这个 post 帮助我使用进度条和地图功能将所有内容放入一个数据框中。

可能会有更好的答案,但到目前为止这对我有用。