如何在具有标题和 json 正文的 R 中发布 API

R A*_*ion 2 api r

如何在 R 中调用 API Post

请求 URL https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment

请求头 Ocp-Apim-Subscription-Key = 一些值 & Content-Type = application/json

正文应用程序/json

{
  "documents": [
    {
      "language": "string",
      "id": "string",
      "text": "string"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

请帮忙!!!

小智 10

这是例子——

request_body <- data.frame(
language = c("en","en"),
id = c("1","2"),
text = c("This is wasted! I'm angry","This is awesome! Good Job Team! appreciated")
)
Run Code Online (Sandbox Code Playgroud)

将请求体(Dataframe)转换为请求体(JSON)

require(jsonlite)
request_body_json <- toJSON(list(documents = request_body), auto_unbox = TRUE)
Run Code Online (Sandbox Code Playgroud)

下面我们调用API(使用add_headers添加请求头)

require(httr)
result <- POST("https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment",
body = request_body_json,
add_headers(.headers = c("Content-Type"="application/json","Ocp-Apim-Subscription-Key"="my_subscrition_key")))
Output <- content(result)
Run Code Online (Sandbox Code Playgroud)

显示输出

输出