'Create own Google Translate API call
I try to call the Google Translate API but always get a 403 error that I didn't provide a valid API key.
I did create one, though, on my Google Cloud Platforms website here: https://console.cloud.google.com/apis/credentials
Here's what I'm doing:
library(jsonlite)
library(httr)
my_text <- c("Hallo Mama", "Ja älskar dig")
my_key <- "MYKEY"
textbody <- toJSON(list(q = my_text,
target = "en"))
translated <- POST(url = paste0("https://translation.googleapis.com/language/translate/v2"),
add_headers("key" = my_key),
content_type("application/json"),
body = textbody,
encode = "json")
But this returns said 403 error, i.e.:
fromJSON(rawToChar(translated$content))
gives:
$error
$error$code
[1] 403
$error$message
[1] "The request is missing a valid API key."
$error$errors
message domain reason
1 The request is missing a valid API key. global forbidden
$error$status
[1] "PERMISSION_DENIED"
Note: the "MYKEY" used above I have of course replaced with my created true API key.
Any ideas what's going on?
Update: the following does work for v2 of the API (but not v3). I was missing te unboxing in the JSON body and I seem to have to put the APIkey into the URL:
textbody <- toJSON(list(q = my_text,
target = "en"),
auto_unbox = TRUE)
translated <- POST(url = paste0("https://translation.googleapis.com/language/translate/v2?key=", my_key),
content_type("application/json"),
body = textbody,
encode = "json")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
