R Application
R Application

Reputation: 31

How to Post API in R having header & json body

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!!!

Upvotes: 3

Views: 13421

Answers (1)

sho
sho

Reputation: 224

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

Upvotes: 11

Related Questions