R 相当于 Python http 请求

问题描述 投票:0回答:1

我目前使用 Python 发出了从 API 获取数据的请求,该请求工作正常。我正在尝试在 R 中制作等效代码,但是当我运行它时它不起作用,有谁知道为什么会发生这种情况?

Python代码:

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)

和我正在尝试的R等效代码:

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)
r python-requests httr
1个回答
0
投票

最终的 JSON 字符串似乎有 1 个额外级别,请求本身应该在

body
arg 中包含所有数据,并且标头是通过
add_headers()
添加的,所以类似于:

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

使用

httr2
你可以尝试:

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()
© www.soinside.com 2019 - 2024. All rights reserved.