Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set GOOGLE_APPLICATION_CREDENTIALS in Python project to use Google API

I am a programming beginner and thing I'm trying to learn how to use google API with Python.

I have:

  1. created a project on Google Cloud and enabled the API that I want to use, Natural Language API.
  2. created a credential and downloaded the credential JSON file, saved it as apikey.JSON
  3. In the Terminal I have ran this command: export GOOGLE_APPLICATION_CREDENTIALS=apikey.JSON, no error popped.

However, even when I ran the simplest of codes for this, I have errors which says the credential variable is not found.

I am not sure what to do now. Please kindly help.

This is my code:

from google.cloud import language

def sentiment_text(text):

    client = language.LanguageServiceClient()

    sentiment = client.analyze_sentiment(text).document_sentiment

    print('Score: {}'.format(sentiment.score))
    print('Magnitude: {}'.format(sentiment.magnitude))

sampletxt='Python is great'

sentiment_text(sampletxt)

And I have errors:

> Traceback (most recent call last):   File
> "/Users/YELI1/Downloads/googlecloud/sentimentanalysis/simple.py", line
> 21, in <module>
>     sentiment_text(sampletxt)
> 
>   File
> "/Users/YELI1/Downloads/googlecloud/sentimentanalysis/simple.py", line
> 5, in sentiment_text
>     client = language.LanguageServiceClient()
> 
>   File
> "/usr/local/lib/python3.6/site-packages/google/cloud/gapic/language/v1/language_service_client.py",
> line 147, in __init__
>     ssl_credentials=ssl_credentials)
> 
>   File "/usr/local/lib/python3.6/site-packages/google/gax/grpc.py",
> line 106, in create_stub
> 
>     credentials = _grpc_google_auth.get_default_credentials(scopes)   File
> "/usr/local/lib/python3.6/site-packages/google/gax/_grpc_google_auth.py",
> line 62, in get_default_credentials
>     credentials, _ = google.auth.default(scopes=scopes)
> 
>   File
> "/usr/local/lib/python3.6/site-packages/google/auth/_default.py", line
> 282, in default
> 
>     raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) google.auth.exceptions.DefaultCredentialsError: Could not
> automatically determine credentials. Please set
> GOOGLE_APPLICATION_CREDENTIALS or explicitly create credential and
> re-run the application. For more information, please see
> https://developers.google.com/accounts/docs/application-default-credentials.

The value is not in the environment

import os 
print(os.environ['GOOGLE_APPLICATION_CREDENTIALS']) 
   File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework‌​/Versions/3.6/lib/py‌​thon3.6/os.py", line 669, in getitem  
raise KeyError(key) from None KeyError: 'GOOGLE_APPLICATION_CREDENTIALS'
like image 942
Liam Avatar asked Aug 04 '17 07:08

Liam


6 Answers

If you're working on a jupyter notebook and want to set GOOGLE_APPLICATION_CREDENTIALS environment variable in Python code :

import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/path/to/file.json"
like image 63
Marius Avatar answered Oct 13 '22 04:10

Marius


I know that this post was answered but the following is a cleaner way to specify the GOOGLE_APPLICATION_CREDENTIALS variable.

client = language.LanguageServiceClient.from_service_account_json("/path/to/file.json")
like image 36
sdikby Avatar answered Oct 13 '22 04:10

sdikby


There is 1 more simpler way of making it working by explicity mentioning Credentials and passing them to client as shown below.

import os
from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file("your-json-path-with-filename.json")
client = language.LanguageServiceClient(credentials=credentials)
like image 22
rishi jain Avatar answered Oct 13 '22 04:10

rishi jain


In case you have the credentials in memory (environment variable for example), and you don't want to create a file especially for it:

from google.cloud import storage
from google.oauth2 import service_account

gcp_json_credentials_dict = json.loads(gcp_credentials_string)
credentials = service_account.Credentials.from_service_account_info(gcp_json_credentials_dict)
client = storage.Client(project=gcp_json_credentials_dict['project_id'], credentials=credentials)

Using python3.7 and google-cloud-storage==1.35.0

like image 23
sheldonzy Avatar answered Oct 13 '22 06:10

sheldonzy


Another way to test this is to go into the terminal and type:

# Linux/Unix
set | grep GOOGLE_APPLICATION_CREDENTIALS 

or

# Windows:
set | Select-String -Pattern GOOGLE_APPLICATION_CREDENTIALS 

This will show you the environment variable and the path where it is located. If this returns nothing then you have not set the variable or you may have the wrong path set

like image 42
seanbrhn3 Avatar answered Oct 13 '22 05:10

seanbrhn3


When your code is running in a local development environment, the best option is to use credentials associated with your Google Account.

  1. Install and initialize the gcloud CLI, if you haven't already.

  2. Create your credential file:

    gcloud auth application-default login
    

A login screen is displayed. After you log in, your credentials are stored in the local credential file used by ADC. You should be then be allowed to automatically determine credentials.

like image 20
Doracahl Avatar answered Oct 13 '22 04:10

Doracahl