2
votes

How to call API Post in R

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

Request headers Ocp-Apim-Subscription-Key = some value & Content-Type = application/json

Body application/json

{
  "documents": [
    {
      "language": "string",
      "id": "string",
      "text": "string"
    }
  ]
}

Please help!!!

1
Don't reinvent the wheel. There's an R package for this API. - hrbrmstr
already know mscstexta4r in R @hrbrmstr - R Application
by not using an existing, working API you most certainly are. - hrbrmstr
if you know how to call in R then please tell me. I already know mscstexta4r in R @hrbrmstr Im not re inventing the wheel - R Application
github.com/philferriere/mscstexta4r/blob/master/R/… seems to show you how to do this and there are dozens of httr::POST examples with JSON content on StackOverflow. You're asking folks to do the work for you. - hrbrmstr

1 Answers

10
votes

Here is the example -

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")
)

Converting the Request body(Dataframe) to Request body(JSON)

require(jsonlite)
request_body_json <- toJSON(list(documents = request_body), auto_unbox = TRUE)

Below we are calling API (Adding Request headers using 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)

Show Output

Output