Python正常运行的API请求转R后失效,求问题排查
求助:Python API请求转R代码后无法正常运行
我用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代码问题出在httr::POST的参数使用上:在httr中,同时传递data和files参数会导致表单结构异常,无法正确构建符合API要求的multipart/form-data请求。Python的requests会自动合并data和files的内容到同一个multipart表单,但httr需要你把所有表单字段(包括普通字段和文件)统一放到body参数中。
修正后的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)) fields_to_extract <- list( list( name = "CURP", description = "Curp string", type = "String" ) ) # 将fields_to_extract转为JSON字符串 fields_json <- toJSON(fields_to_extract, auto_unbox = TRUE) # 构建完整的multipart表单数据,包含普通字段和文件 body_data <- list( fields_to_extract = fields_json, document = upload_file(file_path) ) # 发送POST请求,使用body参数传递所有表单内容 response <- POST(url, headers = headers, body = body_data, encode = "multipart") # 查看响应结果 print(status_code(response)) print(content(response, "text"))
关键修正点:
- 将
fields_to_extract的JSON字符串和文件对象合并到同一个body_data列表中 - 使用
body参数传递所有表单内容,显式指定encode = "multipart"(httr会自动识别列表中的upload_file对象,但显式指定更稳妥) - 去掉了多余的嵌套
list(fields_to_extract = ...),和Python代码保持一致,直接将JSON字符串作为fields_to_extract字段的值
内容的提问来源于stack exchange,提问作者Jorge Hernández
相关产品推荐
相关产品推荐

