使用R在API中上传CSV文件

时间:2018-12-12 10:45:00

标签: r

有人可以提供有关使用R连接API以及使用R将包含约2k条记录的文件上传到API的代码的帮助吗?

我尝试了以下代码,但没有帮助:

apiurl <- "https://api.thomsonreuters.com/permid/match/file"
Records <- "C:\\Users\\U6028364\\Downloads\\Organization_input_template_with_examples.csv
  resp <- POST(apiurl,body=list(

                    addressFile=upload_file(Records),
                    Content-Type="multipart",


      ))

stop_for_status(resp)
get_data <- content(resp,"text")

谢谢 乔塔姆

2 个答案:

答案 0 :(得分:1)

尝试在评论中用段落解释以下内容会很痛苦,因此请看一下:

api_url <- "https://api.thomsonreuters.com/permid/match/file"

records <- "C:\\Users\\U6028364\\Downloads\\Organization_input_template_with_examples.csv"

httr::POST(
  url = api_url,
  body = list(
    addressFile = httr::upload_file(records),
  ),
  encode = "multipart"
) -> resp

httr::stop_for_status(resp)

get_data <- content(resp, "text")

唯一真正的变化是您需要使用encode参数(而且,您在问题代码中错过了")。

我无权访问TR API,因此无法测试。但是,https://docs-developers.thomsonreuters.com/1544617757924/45690/wwhelp/wwhimpl/js/html/wwhelp.htm#href=PermID%20Service/PermID%20APIs%20User%20Guide.1.27.html说这是curl命令行来完成您要尝试的操作:

curl -X POST https://api.thomsonreuters.com/permid/match/file 
     -H "Content-Type: multipart/form data" 
     -H "x-openmatch-numberOfMatchesPerRecord: 1" 
     -H "x-openmatch-datatype: Organization" 
     -H "X-AG-Access-Token: <token>" 
     -F file=@OrgRecords.csv

在这种情况下,您可能会丢失一些东西,并且使用了不正确的body,因此这可能会更好:

httr::POST(
  url = api_url,
  httr::add_headers(
    `X-AG-Access-Token` = "YOUR_ACCESS_TOKEN_WHICH_YOU_RLY_SHLDNT_PUT_DIRECTLY_IN_R_SCRIPTS"
  )
  body = list(
    file = httr::upload_file(records)
  ),
  encode = "multipart"
) -> resp

我不知道是否需要其他“ openmatch”标头。

答案 1 :(得分:0)

以下是我尝试执行的操作,但它给出的错误如下:as.request(config)中的错误:找不到对象'httr'

httr::POST(
  url = api_url,
  httr:add_headers(
    X-AG-Access-Token : "abcd"

  ),
  body = list(
    file = httr::upload_file(records)
  ),
  encode = "multipart"
) -> resp