HTTP POST request using R httr2 package

392 Views Asked by At

For a project I need to access data from the Global Forest Watch (GFW), using its AP. I first need to obtain a token through a POST request.

The GFW indicates the following request :

curl --location --request POST 'https://data-api.globalforestwatch.org/auth/token' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'username=<YOUR_USERNAME>' \ --data-urlencode 'password=<YOUR_PASSWORD>'

As I will process the data in R, I want to obtain this token using R functions.

I tried to use the httr2 package to run this request :

req_token = request('https://data-api.globalforestwatch.org/auth/token') %>%
  req_headers("Content-Type" = "application/x-www-form-urlencoded") %>% 
  req_body_json(list(username = "username", password = "password")) 
resp_token = req_perform(req_token)

However it returns HTTP 422 error. I have the feeling it is related to the format of the body, not adapted to the "data-urlencode".

I have also tried using httr package, by providing my password and username in a body or through httr:::authenticate() (in comment here).

url = "https://data-api.globalforestwatch.org/auth/token"
custom_headers = c("Content-Type" =  "application/x-www-form-urlencoded")
data = list(username = "username", password = "password")
username = "username"
password = "password"
resp = httr::POST(url, 
                  body = data, 
                  add_headers("Content-Type" = "application/x-www-form-urlencoded"))
                  #authenticate(username, password, type = "basic"))

Again, this does not work. resp returns failed status, with message "field required" of type "value_error.missing" for username and password.

It might be a silly question, but I am quite new to API requests in R.

0

There are 0 best solutions below