Use google cloud translation api using api key

Question:

I made myself a free account so I can experiment a little bit with Google Cloud Translation API. I generated myself a key from Service account, stored it into a json file, loaded it and everything seems to be working fine. Snippet from my code:

import os
from google.cloud import translate_v2

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r"google.json"

print(os.getenv('GOOGLE_APPLICATION_CREDENTIALS'))
translate_client = translate_v2.Client()

text = "Redaksia e IRL-së pas publikimit të skandalit të quajtur “Gjaku i Pistë”, sonte ka dalë me një"
target = 'en'
output = translate_client.translate(text, target_language=target)
print(output)

However, I saw that in Credentials, I can generate an API key and now I’d like to use that API key so I can translate and avoid the json file. The problem is, I tried to find a way of how can I use this api key but none the less, couldn’t find any! I tried to pass the key in the constructor of the Client as translate_client = translate_v2.Client(credentials=API_KEY) but I got the error

ValueError: This library only supports credentials from google-auth-library-python.

Has someone used api key for translation api from google and if so, how? If not, is the json file from service account the only way to authenticate against this service?

Asked By: anthino12

||

Answers:

That exact error means that it does not support API keys. The possible methods of authentication are listed on this page.

If your only requirement is to not include a JSON file then you can put the JSON contents in a python dict and use the following method to create a credentials object which you can pass to the instantiation of the translate client.

Note that you should never put this dict in any publicly accessible place (same goes for the API key) as it will allow access to whatever the serviceaccount or API key in question has access to.

Docs

sa_dict = {
  "type": "xxxx",
  "project_id": "xxx",
  "private_key_id": "xxx",
  "private_key": "xxxxxx",
  "client_email": "[email protected]",
  "client_id": "xxxxxxxxxx",
  "auth_uri": "xxxxxx",
  "token_uri": "xxxxxx",
  "auth_provider_x509_cert_url": "xxxxx",
  "client_x509_cert_url": "xxxxx.iam.gserviceaccount.com"
}

credentials = service_account.Credentials.from_service_account_info(sa_dict)
translate_client = translate_v2.Client(credentials=credentials)

You other option would be to switch to the general Google API library, called google-api-python-client but this does not have the same optimizations that the specific google-cloud-translate has.

The github repo for this library has an extremely simple sample here and full documentation here

Answered By: Edo Akse