Search code examples
rapicurlhttr

How to use R to analyze text with TextRazor API?


I'm new to using API's and I hope you can help me. I am trying to send a POST request to TextRazor API via httr Package in R but I don't get it to work. What do I do wrong?

library(httr)
library(RCurl)    

key <- "MY API KEY"
text <- "text=Spain's stricken Bankia expects to sell off its vast portfolio of industrial holdings that includes a stake in the parent company of British Airways and Iberia"
extractors <- "&extractors=entities"

doc <- POST("https://api.textrazor.com",
 add_headers("x-textrazor-key" = key),
 body = paste0(text, extractors)
 )
 doc


Response [https://api.textrazor.com/]
  Date: 2015-11-16 14:29
  Status: 200
  Content-Type: application/json
  Size: 3.07 kB

When I run this code I get Status Code 200 which is good. But somehow the result (doc) does not have a list-element called 'response'.

API Documentation can be found here https://www.textrazor.com/docs/rest

I just don't know what I am doing wrong.

I would apreciate your help very much. Thanks in advance.


Solution

  • You need to make sure the request body is properly form encoded so the server can parse it. The 'httr' package makes this easy by allowing you to pass in a list of paramaters and handling encoding internally. The following worked for me:

    doc <- POST("https://api.textrazor.com",
            add_headers("x-textrazor-key" = key),
            body = list(text=raw_text, extractors="entities"),
            encode = "form")
    
    content(doc)$response$entities[[1]]$entityId