Peter Tat
Peter Tat

Reputation: 21

How to make a POST call using Google Translate API using R

if (!require("httr")) {
  install.packages("httr", repos="http://cran.rstudio.com/")
  library("httr")
}

if (!require("jsonlite")) {
  install.packages("jsonlite", repos="http://cran.rstudio.com/")
  library("jsonlite")
}

My Get works fine...

api <- "xxxxxxxxxxxxxxxx"
url <-paste0(
   "https://translation.googleapis.com/language/translate/v2/languages/? 
   key=",api
 )
data3 <- GET(url)
data3 <- content(data3)
data3 <- as.data.frame(data3)
data3 <- as.data.frame(t(data3))

My POST does not work

url <- paste0(
   "https://translation.googleapis.com/language/translate/v2/detect/?key=",api
 )
request_body <- data.frame(message = "hello")
request_body_json <- toJSON(list(documents = request_body), auto_unbox = TRUE)
result <- POST(url, body = request_body_json)

i'm trying to get the language detect to work my understanding is that we need to post in a JSON file to google API however i'm getting an error #"code": 400, #"message": "Required Text"

I was hoping someone can point me in the right direction I understand there is an R package but I'm trying to learn how to do it without the package because sometimes the google or microsoft updates their API and the # package does not get updated (Example: TranslateR doesn't support Microsoft ever since the API update, so I want to learn how to do this manually as much # as possible https://cloud.google.com/translate/docs/quickstart?csw=1 https://translation.googleapis.com/$discovery/rest?version=v2

Upvotes: 1

Views: 889

Answers (1)

Peter Tat
Peter Tat

Reputation: 21

nevermind... i figured it out after a few hours hacking around.. =)

TEXT1 = "Testate con lo smartphone si sente decisamente bene"
TEXT1 <- str_replace_all(TEXT1, " ", "%20")
test1 <- paste0("https://translation.googleapis.com/language/translate/v2?target=en&key=xxxxxxxxx&q=", TEXT1)
result2 <- POST(test1)
result2 <- content(result2)
result2 <- as.data.frame(result2)

Upvotes: 1

Related Questions