rpython-requestshttr

R equivalent for Python http request


I currently made a request to get data from an API using Python, which works correctly. I'm trying to make an equivalent code in R but when I run it it doesn't work, does anyone know why this happened?

The Python code:

import requests
import json

url = 'https://api.reformhq.com/v1/api/extract'
reform_api_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
file_path = 'curp/image_idx_2.jpeg'

headers = {
    'Authorization': f'Bearer {reform_api_key}',
}

fields_to_extract = [
    {
        "name": "CURP",
        "description": "Curp string",
        "type": "String"
    }
]

form_data = {
    'document': (open(file_path, 'rb')),
}

data = {
    'fields_to_extract': json.dumps(fields_to_extract)
}

response = requests.post(url, headers=headers, data=data, files=form_data)

print(response.status_code)
print(response.text)

and the R equivalent code I'm trying:

library(httr)
library(jsonlite)

url <- 'https://api.reformhq.com/v1/api/extract'
reform_api_key <- 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
file_path <- 'curp/image_idx_2.jpeg'


headers <- c('Authorization' = paste('Bearer', reform_api_key, sep=' '))

fields_to_extract <- list(
  list(
    name = "CURP",
    description = "Curp string",
    type = "String"
  )
)

form_data <- list(
  document = upload_file(file_path)
)

json_data <- toJSON(list(fields_to_extract = fields_to_extract), auto_unbox = TRUE)


data <- list(
  fields_to_extract = json_data
)

x <- POST(url,headers=headers, data=data, files=form_data)

Solution

  • That final JSON string seems to have 1 extra level, request itself should have all data in body arg and headers are added through add_headers(), so something like:

    POST(url, 
         add_headers(headers), 
         body = list(fields_to_extract = toJSON(fields_to_extract, auto_unbox = TRUE), document = upload_file(file_path)))
    

    With httr2 you could try:

    library(jsonlite)
    library(httr2)
    
    url <- 'https://api.reformhq.com/v1/api/extract'
    reform_api_key <- 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    file_path <- 'curp/image_idx_2.jpeg'
    
    fields_to_extract <- list(
      list(
        name = "CURP",
        description = "Curp string",
        type = "String"
      )
    )
    
    resp <- 
      request(url) |>
      req_auth_bearer_token(reform_api_key) |>
      req_body_multipart(fields_to_extract = toJSON(fields_to_extract, auto_unbox = TRUE), 
                         document = curl::form_file(file_path)) |>
      req_perform()