我尝试使用R中的HTTR包来模仿CURL请求。这是propbulica的选举API。
propublica.github.io/campaign-finance-api-docs /
命令行请求记录如下:
curl "https://api.propublica.org/campaign-finance/v1/2016/president/totals.json" -H "X-API-Key: PROPUBLICA_API_KEY"
我在使用R时对此的模仿如下:
require(httr)
api_key <- "my key"
path <- "https://api.propublica.org/campaign-finance/v1/2016/president/totals.json"
data <- GET(path, add_headers("X-API-Key", .headers = api_key))
content(data)
这会返回&#34;禁止&#34;。
ProPublica的Derek Willis告诉我,我的密钥是有效的。答案 0 :(得分:4)
我制作了curlconverter
包以帮助解决这类问题:
library(curlconverter)
cmd <- 'curl "https://api.propublica.org/campaign-finance/v1/2016/president/totals.json" -H "X-API-Key: PROPUBLICA_API_KEY"'
parsed_cmd <- straighten(cmd)
str(parsed_cmd)
## List of 1
## $ :List of 5
## ..$ url : chr "https://api.propublica.org/campaign-finance/v1/2016/president/totals.json"
## ..$ method : chr "get"
## ..$ headers :List of 1
## .. ..$ X-API-Key: chr "PROPUBLICA_API_KEY"
## ..$ url_parts:List of 9
## .. ..$ scheme : chr "https"
## .. ..$ hostname: chr "api.propublica.org"
## .. ..$ port : NULL
## .. ..$ path : chr "campaign-finance/v1/2016/president/totals.json"
## .. ..$ query : NULL
## .. ..$ params : NULL
## .. ..$ fragment: NULL
## .. ..$ username: NULL
## .. ..$ password: NULL
## .. ..- attr(*, "class")= chr [1:2] "url" "list"
## ..$ orig_curl: chr "curl \"https://api.propublica.org/campaign-finance/v1/2016/president/totals.json\" -H \"X-API-Key: PROPUBLICA_API_KEY\""
## ..- attr(*, "class")= chr [1:2] "cc_obj" "list"
## - attr(*, "class")= chr [1:2] "cc_container" "list"
actual_function <- make_req(parsed_cmd)[[1]] # returns a list as it's vectorized
拨打电话 - 它应该“正常工作”
# actual_function() # not going to work here since it's not a real api key
看看里面是什么:
actual_function
## function ()
## httr::VERB(verb = "GET", url = "https://api.propublica.org/campaign-finance/v1/2016/president/totals.json",
## httr::add_headers(`X-API-Key` = "PROPUBLICA_API_KEY"))
## <environment: 0x7f8d90aeee98>
它旨在使用浏览器开发者工具窗口中的“复制为cURL”字符串。
答案 1 :(得分:0)
GET(path, config = list(token = api_key))
这假设“我的密钥”是一个oauth令牌环境。需要了解更多关于API的信息。请参阅httr中的github示例,了解密钥生成和api握手。