401 error with OAuth2 token

882 views
Skip to first unread message

Yoonjung Cho

unread,
Mar 3, 2020, 8:56:36 AM3/3/20
to Google Cloud Translation API
I get 401 error with code below.
GOOGLE_APPLICATION_CREDENTIALS exported.
What would be a problem?
Thanks in advance.

(project id and token masked)

import requests
url = "https://translation.googleapis.com/v3beta1/projects/p*******3/locations/global:translateText"
token = "4/xAG_QxNqxN5IlNPx96ge******nM5mSmWt8lGZY0Zv-j1Wom196DFQ"
headers = {"Authorization": "Bearer " + token, 
        "Content-Type": "application/json; charset=utf-8"}        
data = {
  "model": "projects/p*******3/locations/global/models/general/base",
  "sourceLanguageCode": "en",
  "targetLanguageCode": "de",
  "contents": ["Come here!"]
}
res = requests.post(url, headers=headers, data=data)
print(res.text)


Response:
{
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  } 
} 

Yoonjung Cho

unread,
Mar 5, 2020, 10:40:57 AM3/5/20
to Google Cloud Translation API
I solved the problem. What I used was a code, not access token. According to this document(https://developers.google.com/youtube/v3/guides/auth/installed-apps?hl=ko), I got access_token with code and it worked.

dhino...@gmail.com

unread,
Jul 19, 2021, 1:31:24 PM7/19/21
to Google Cloud Translation API
Hi,
Can you elaborate further on your solution? Perhaps as before, placing the entire code and obfuscating your credentials?
Best,
Daniel

Jun (Cloud Platform Support)

unread,
Jul 20, 2021, 6:50:30 PM7/20/21
to Google Cloud Translation API
Hi Daniel, 

I believe he followed the instructions at [1] for obtaining OAuth 2.0 access tokens, but you can wait for elaboration from the original poster on his solution. 

Reply all
Reply to author
Forward
0 new messages