jgozal
jgozal

Reputation: 1582

Making a GET request in R

I've been playing a little with httr and rcurl and cannot manage to translate the following curl GET request into R:

curl -X GET --header 'Accept: application/json' --header 'Authorization: Bearer 31232187asdsadh23187' 'https://this.url.api.com:334/api/endpoint'

Particularly, I've been having some trouble to pass the Authorization option as I was not able to find the equivalent parameter in neither of the libraries. It might be a custom header maybe?

Upvotes: 8

Views: 25465

Answers (4)

sbha
sbha

Reputation: 10432

The httr2 package (a rewrite of httr) has the curl_translate function which takes a curl command generated from copy as curl in a browser's developer tools and translates it into a httr2 request. It is influenced by the curlconverter function cited in other answers.

resp <- 
  request("https://stackoverflow.com/questions/35559913/making-a-get-request-in-r") |> 
  req_headers(
    `User-Agent` = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:121.0) Gecko/20100101 Firefox/121.0",
    Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
    `Accept-Language` = "en-US,en;q=0.5",
    `Accept-Encoding` = "gzip, deflate, br",
    `Upgrade-Insecure-Requests` = "1",
    DNT = "1",
    `Sec-GPC` = "1",
  ) |> 
  req_perform()

Upvotes: 0

Corina Roca
Corina Roca

Reputation: 546

I agree with sckott answer. I don't know too much about the maintenance and officiallity of curlconverter, but to complete httr function i will add few lines more.

getInfoInJson <- httr::GET('https://this.url.api.com:334/api/endpoint', 
      accept_json(), 
      add_headers('Authorization' = 'Bearer 31232187asdsadh23187'))

 #safe the info in a json object 
 jsonInfoImg <- content(getInfoInJson, type="application/json")

Hope it helps.

Upvotes: 1

JackStat
JackStat

Reputation: 1653

Try out the new and further improving curlconverter package. It will take a curl request and output an httr command.

#devtools::install_github("hrbrmstr/curlconverter")

library(curlconverter)

curlExample <- "curl -X GET --header 'Accept: application/json' --header 'Authorization: Bearer 31232187asdsadh23187' 'https://this.url.api.com:334/api/endpoint'"

resp <- make_req(straighten(curlExample))
resp

Upvotes: 3

sckott
sckott

Reputation: 5913

httr::GET('https://this.url.api.com:334/api/endpoint', 
      accept_json(), 
      add_headers('Authorization' = 'Bearer 31232187asdsadh23187'))

See also https://github.com/hrbrmstr/curlconverter

Upvotes: 9

Related Questions