I trying to imitate a CURL request using the HTTR package in R. It's for propbulica's election API.
propublica.github.io/campaign-finance-api-docs/
The command line request is documented as follows:
curl "https://api.propublica.org/campaign-finance/v1/2016/president/totals.json" -H "X-API-Key: PROPUBLICA_API_KEY"
My imitation of this in using R is as follows:
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)
This returns a "forbidden".
Derek Willis, at ProPublica tells me my key is valid.
I made the curlconverter
package to help with just this sort of thing:
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
make the call - it should “just work”
# actual_function() # not going to work here since it's not a real api key
see what’s inside:
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>
It's designed to work with "Copy as cURL" strings from browser Developer Tools windows.